Hi I'm learning Python via a Youtube Tutorial series and the tutorial I just viewed explained how to print tuples embedded within a list. The publisher of video explains two ways, specifically:
>>> a = [(1,2,3), (4,5,6), (7,8,9)]
>>> for (b, c, d) in a:
... print(b,c,d)
...
1 2 3
4 5 6
7 8 9
>>> for nums in a:
... a,b,c = nums
... print(a,b,c)
...
1 2 3
4 5 6
7 8 9
I attempted a third way:
>>> for nums in a:
... a,b,c = nums
... print(nums)
but received this error
"Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not iterable"
I sense that the takeaway is that I should make sure to always print tuples in tuple form but that seems like if could be really tedious if it were a really long tuple (or list of tuples). What is wrong with my attempt?
First of all, this works just fine
a = [(1,2,3), (4,5,6), (7,8,9)]
for nums in a:
a,b,c = nums
print(nums)
(1, 2, 3)
(4, 5, 6)
(7, 8, 9)
Second, if don't have the need to expand the tuple (or in general any iterable), you don't have to. This is equivalent to the snippet above. The for-loop just iterates across the first level of objects, whatever that is (tuples in your case):
a = [(1,2,3), (4,5,6), (7,8,9)]
for nums in a:
print(nums)
(1, 2, 3)
(4, 5, 6)
(7, 8, 9)
Third, it's a bad practice to reuse the variable a in the loop that you've defined outside the loop. Afterwards, outside the loop, a will be what it was during the last iteration of the loop (which is 7). That's a drawback of duck typing, i.e. missing type declaration in python compared to C for example
a = [(1,2,3), (4,5,6), (7,8,9)]
for nums in a:
a,b,c = nums
print(nums)
print a
(1, 2, 3)
(4, 5, 6)
(7, 8, 9)
7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With