1

I have been using PHP for several years and now, I am trying to shift to a new one. I am interested of learning python.

In PHP, we use foreach something like this:

<?php
$var = array('John', 'Adam' , 'Ken');
foreach($var as $index => $value){
   echo $value; 
}

How do we integrate this code in python?

Touheed Khan
  • 2,149
  • 16
  • 26
smzapp
  • 809
  • 1
  • 12
  • 33
  • 9
    Possible duplicate of [Is there a 'foreach' function in Python 3?](https://stackoverflow.com/questions/18294534/is-there-a-foreach-function-in-python-3) – Qirel Jun 07 '17 at 05:49

4 Answers4

4

Python doesn't have a foreach statement per se. 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)

Reference: Is there a 'foreach' function in Python 3?

NID
  • 3,238
  • 1
  • 17
  • 28
2

The equivalent of the foreach statement is actually the python for statement.

e.g.

>>> items = [1, 2, 3, 4, 5]
>>> for i in items:
...     print(i)
...
1
2
3
4
5

It actually works for all iterables in python, including strings.

>>> word = "stackoverflow"
>>> for c in word:
...     print(c)
...
s
t
a
c
k
o
v
e
r
f
l
o
w

However, it is worth noting that when using the for loop in this way you are not editing the iterable's values in place as they are a shallow copy.

>>> items = [1, 2, 3, 4, 5]
>>> for i in items:
...     i += 1
...     print(i)
... 
2
3
4
5
6
>>> print(items)
[1, 2, 3, 4, 5]

Instead you would have to use the iterable's index.

>>> items = [1, 2, 3, 4, 5]
>>> for i in range(len(items)):
...     items[i] += 1
... 
>>> print(items)
[2, 3, 4, 5, 6]
joshuatvernon
  • 1,530
  • 2
  • 23
  • 45
0

See documentation here: https://wiki.python.org/moin/ForLoop

collection = ['John', 'Adam', 'Ken']
for x in collection:
    print collection[x]
Sergei Kasatkin
  • 385
  • 2
  • 11
0

If you need get also index, you can try this:

var = ('John', 'Adam' , 'Ken')
for index in range(len(var)):
    item = var[index]
    print(item)