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

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) {
    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,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
6 views
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 objects.it is ...READ MORE

answered Apr 12 in Python by rajesh
• 1,210 points
50 views
+1 vote
1 answer

How to check if a string is null in python

Try this: if cookie and not cookie.isspace(): # the ...READ MORE

answered Aug 20, 2018 in Python by Priyaj
• 56,120 points
772 views
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
23 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,710 points
224 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,710 points
38 views

© 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.