Python Forum
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
For x in [1,2,3]
#1
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?
Reply
#2
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
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
Ok I get it now, thank you!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020