Python Forum

Full Version: Best form of iterating over a lsit of lists
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
eventually you can use named tupe
 
from collections import namedtuple

Pet = namedtuple('Pet', ['name', 'animal', 'weight'])

pets = (Pet('Garfield', 'cat', 4), Pet('Pluto', 'dog', 10))
for mypet in pets:
    print(mypet)
    print('{} is a {} and its weight is {}'.format(*mypet))
    print(mypet.name, mypet.animal, mypet.weight)
Output:
Pet(name='Garfield', animal='cat', weight=4) Garfield is a cat and its weight is 4 Garfield cat 4 Pet(name='Pluto', animal='dog', weight=10) Pluto is a dog and its weight is 10 Pluto dog 10
Use the first one in a loop,the all will work the same.
for name, species, weight in pets:
    print(name, species, weight)
The name of the this stuff is called tuple assignment and tuple unpacking.
>>> info = ('julia', 'borger', '27')
# The normal way
>>> name, surname, birth_year = info
>>> name
'julia'
>>> surname
'borger'
>>> birth_year
'27'
# Can do this,but not so common
(name, surname, birth_year) = info

# Can do this,whaaat?
[name, surname, birth_year] = info
There's no real difference. You might be wasting a little time with the latter two, and they look a little odd, but there's no real difference.
I've done what I should probably have done in the first place; read the spec. I think I basically understand now but htere's one thing still bothering me.

There is a difference between () and [] on the LHS of an assignment but it's quite subtle.
(a) = is the same as a =
[a] = requires an iterable on the RHS (with just one value)
So (a) = 2 is valid but [a] = 2 is not.

I'm guessing this use of parenthesis is to be consistent with the rules for creating tuples and lists. In (1,2) the parentheses don't make this a tuple, the comma does. The parentheses are, actually (redundant) "ordering" parentheses as in (2 + 3). On the LHS they do the same thing.
E.G.
a,(b,) = 1, 2      #invalid
a,(b,) = 1, 2,     #invalid
a,(b,) = 1, (2,)   #OK
a,(b,) = 1, (2)    #invalid
a, b   = 1, 2,     #OK
a, b,  = 1, 2      #OK
But, what I still don't get is why allow [] on the RHS at all. a, requires and iterable on the RHS just like [a]. I.E.:
(a) = 1,  #a is a tuple.
[b] = 2,  #b is an integer
#but so is c in 
c, = 1,
I can't see a need for [] on the LHS so it seems odd to allow them. Especially given the confusion with lists and tuples.
Maybe [] are allowed on the LHS for slice assignment? some_list[2:5] = range(4)
You're right, my statement "I can't see a need for [] on the LHS" was to broad. I do see their use in a slice assignment. But still not in assignment to a target list.
Pages: 1 2