Python Forum

Full Version: For x in [1,2,3]
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Since most of the python tutorials are in English and that's not my main lenguage, i'm very confused about the "For x in [...]" Usage.
Does it work like the "for x in range()" command, with x cycling through every integer from 0 and up or does it work by assigning x the specific values within the list?
for loop loops over any iterable object.

It could be a list, dictionary, tuple, string and so on. Depending on the Python's version the loop over a dictionary will be in random order.

In [1]: from string import ascii_uppercase, ascii_lowercase

In [3]: for c in zip(ascii_uppercase, ascii_lowercase):
   ...:     print(''.join(c), end=' ')
   ...:     
Aa Bb Cc Dd Ee Ff Gg Hh Ii Jj Kk Ll Mm Nn Oo Pp Qq Rr Ss Tt Uu Vv Ww Xx Yy Zz

In [4]: list(zip(ascii_uppercase, ascii_lowercase))
Out[4]: 
[('A', 'a'),
 ('B', 'b'),
 ('C', 'c'),
 ('D', 'd'),
 ('E', 'e'),
 ('F', 'f'),
 ('G', 'g'),
 ('H', 'h'),
 ('I', 'i'),
 ('J', 'j'),
 ('K', 'k'),
 ('L', 'l'),
 ('M', 'm'),
 ('N', 'n'),
 ('O', 'o'),
 ('P', 'p'),
 ('Q', 'q'),
 ('R', 'r'),
 ('S', 's'),
 ('T', 't'),
 ('U', 'u'),
 ('V', 'v'),
 ('W', 'w'),
 ('X', 'x'),
 ('Y', 'y'),
 ('Z', 'z')]
In [5]: for x in [0,1,2,3,4,5]:
   ...:     print(x)
   ...:     
0
1
2
3
4
5

In [6]: for x in range(6):
   ...:     print(x)
   ...:     
0
1
2
3
4
5
Yes, is the same
Ok I get it now, thank you!