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 ariaholic
• 7,340 points
89 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 in Python by Junaid
44 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 27 in Python by Olly
68 views
0 votes
1 answer
0 votes
3 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 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 349 views
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 17, 2018 in Python by charlie_brown
• 7,720 points
628 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 20, 2018 in Python by charlie_brown
• 7,720 points
98 views