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:

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,320 points

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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) {

// C#
foreach (String val in array) {

// Python
for val in array:

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,710 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
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
0 votes
1 answer
0 votes
2 answers

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

  Tuple is a collection of Python is ...READ MORE

answered Apr 12 in Python by rajesh
• 1,210 points
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 1,400 points
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,710 points
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,710 points

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.