2

Hard to describe it, ref below codes, pls

For the var item1, I wonder:

Section1, item1's value is an element of lst, a tuple. but from Section2, items1's value goes to next level, is an element of an element of lst.

how to understand this?

 import random

 lst1 = [random.randint(1, 100) for i in range(10)]
 lst2 = [random.randint(1, 100) for i in range(10)]
 lst = list(zip(lst1, lst2))

 print(lst)

 # section 1
 for item1 in lst:
     print(item1)

 # section 2
 for item1, item2 in lst:
     print(item1, item2)

output example:

[(34, 85), (9, 18), (56, 89), (69, 82), (21, 69), (21, 46), (39, 78), (19, 27), (33, 71), (94, 2)]

section1:

(34, 85)
...
(94, 2)

section2:

34 85
...
94 2

how come from section1 item1 = (34, 85) but item1 just = 34 from section2

Gang
  • 2,658
  • 3
  • 17
  • 38
  • We're going to need to see some code, your expectations, your actual results, and your thoughts and failed attempts on addressing the situation. – sorak Mar 21 '18 at 03:36
  • https://stackoverflow.com/questions/10867882/tuple-unpacking-in-for-loops is very relevant – michaelrccurtis Mar 21 '18 at 03:51

1 Answers1

1

lst is a list of tuple

[(34, 85), (9, 18)] 

for item1 in lst: item1 is a tuple (34, 85)

for item1, item2 in lst: item1 is first element of the tuple (item, item2), e.g (34, 85)

tuple in python is flexible, I will expand a bit.

empty tuple: a = ()

1 item tuple: a = (1,) or b = 1, or c = [], but not a = (1)

for our cases here 2 items tuple:

(34, 85) is the same as 34, 85

(item1, item2) is same as item1, item2

Gang
  • 2,658
  • 3
  • 17
  • 38
  • thanks, I know, but...how come the item1 changed from tuple to an element of the tuple automatically? after just add an item2 follow it! – Weijianzhong Mar 21 '18 at 08:18
  • My point is, from "for item1 in lst:" the item1 point to a tuple, but just add a item2 after item1, likes "for item1, item2 in lst:", then the item1 point to a element of the tuple! – Weijianzhong Mar 21 '18 at 08:51
  • I want to know the mechanism, of item1 point to where of the lst. – Weijianzhong Mar 21 '18 at 08:53