Is there a foreach function in python and is there a way to implement it if there isnt any

0 votes

When the situation for a 'foreach' arises  I've normally implemented in javascript, but I've always thought it would be convenient. This is a small example of a foreach function

def foreach(fn,iterable):
    for y in iterable:
        fn(y)

The function just works on every element and doesn't yield or return anything, I think it should be a built-in function and should be faster when implementing with pure pytho

Aug 31, 2018 in Python by aryya
• 7,450 points
784 views

1 answer to this question.

0 votes

Every occurence of "foreach" I've seen (PHP, C#, ...) does basically the same as pythons "for" statement.

These are more or less equivalent:

// PHP:
foreach ($array as $val) {
    print($val);
}

// C#
foreach (String val in array) {
    console.writeline(val);
}

// Python
for val in array:
    print(val)

So, yes, there is a "foreach" in python. It's called "for".

What you're describing is an "array map" function. This could be done with list comprehensions in python:

names = ['tom', 'john', 'simon']

namesCapitalized = [capitalize(n) for n in names]
answered Aug 31, 2018 by charlie_brown
• 7,720 points

Related Questions In Python

0 votes
1 answer

Is there a way to list out in-built variables and functions of Python?

The in-built variables and functions are defined ...READ MORE

answered May 14, 2019 in Python by Junaid
1,801 views
0 votes
1 answer

Is there a way to loop between 0 and 1 by 0.1 in python?

You can use the linespace function. It ...READ MORE

answered May 28, 2019 in Python by Olly
2,706 views
0 votes
1 answer
0 votes
4 answers

What is a Tuple in Python and how to use it?

Tuples  are a  Unchanging sequence of values, ...READ MORE

answered Jun 21, 2020 in Python by sahil
• 580 points
1,424 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,076 views
0 votes
1 answer
0 votes
1 answer

How to handle AssertionError in Python and find out which line or statement it occurred on?

Use the traceback module: import sys import traceback try: ...READ MORE

answered Dec 18, 2018 in Python by charlie_brown
• 7,720 points
5,376 views
0 votes
1 answer

What is the preferred way to concatenate strings in python??

If the strings you are concatenating are ...READ MORE

answered Dec 21, 2018 in Python by charlie_brown
• 7,720 points
626 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP