Home > front end >  For loop syntax conventions
For loop syntax conventions

Time:06-21

In python when iterating with a for loop, when do we use for x in y versus for x,y in z.

My guess is that it depends on the iterable, and if so, could you explain to me the general conventions?

i.e when you use the enumerate function it's for x,y, in z.

Thanks all

CodePudding user response:

you generally provide a pattern for left side of in, to capture a structure from iterable.

iterating over names = ['joe', 'chloe', 'karen'] is something you already know.

however you can capture any number of linear values.

>>> res = [['joe',1,2], ['chloe',2,3]]
>>> for name, tag1, tag2 in res:
...     print(name, tag1, tag2)
...
joe 1 2
chloe 2 3

or,

>>> res = [['joe', 1,2,3], ['chloe', 3,4]]
>>> for name, first, *rest in  res:
...     print(name, first, rest)
...
joe 1 [2, 3]
chloe 3 [4]

unpacking a dict is same as list.

>>> tps = [('adam', 31, {'a': '1', 'b': 2}), ('karen', 21, {'b': 3, 'a': 9})]

>>> for name, age, keys in tps:
...     print(name, age, keys['a'])
...
adam 31 1
karen 21 9


>>> for name, age, keys in tps:
...     print(name, age, [k for k in keys]) #nested for loop
...
adam 31 ['a', 'b']
karen 21 ['b', 'a']


>>> for name, age, *keys in tps: # * puts result in [] container
...     print(name, age, [k for k in keys])
...
adam 31 [{'a': '1', 'b': 2}]
karen 21 [{'b': 3, 'a': 9}]

enumerate object

 |  The enumerate object yields pairs containing a count (from start, which
 |  defaults to zero) and a value yielded by the iterable argument.
 |
 |  enumerate is useful for obtaining an indexed list:
 |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...

so, one can unpack enumerate(ys) as x, y where x is index of y in ys collection.

  • Related