Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

When I meet the situation I can do it in javascript, I always think if there's a foreach function it would be convenience. By foreach I mean the function which is described below:

def foreach(fn,iterable): 

    for x in iterable: 

      fn(x)

they just do it on every element and didn't yield or return something, I think it should be a built-in function and should be faster than writing it with pure Python, but I didn't found it on the list, or it just called another name? or I just miss some points here?

Maybe I got wrong, cause calling a function in Python cost high, definitely not a good practice for the example. Rather than an out loop, the function should do the loop inside its body looks like this below which already mentioned in many python's code suggestions:

def fn(*args):

    for x in args:

       do something

but I thought for each is still welcome base on the two facts:

  1. In normal cases, people just don't care about the performance

  2. Sometimes the API didn't accept iterable object and you can't rewrite its source.

closed

1 Answer

0 votes
by (106k points)
selected by
 
Best answer

In Python, there is not a foreach statement. It has for loops built into the language.

for element in iterable:

operate(element)

If you really wanted to, you could define your own foreach function:

def foreach(function, iterable):

for element in iterable:

function(element)

As a side note, the for element in iterable syntax comes from the ABC programming language, one of Python's influences.

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
asked Jan 13, 2021 in Python by ashely (50.2k points)
0 votes
4 answers
0 votes
1 answer
0 votes
1 answer
asked Sep 10, 2019 in Python by Sammy (47.6k points)

Browse Categories

...