Reputation: 57
first of all, thank you for your help in advance. I am novice to coding and currently studying Python using the book, 'Automate the Boring Stuff with Python' and I have a conceptual question on multiple assignment. https://automatetheboringstuff.com/chapter4/
The book explains that: 'you could type this line of code:
>>> cat = ['fat', 'orange', 'loud']
>>> size, color, disposition = cat
' But I am not sure the purpose of this multiple assignment.
Initially, I thought I could call the string values after the assignment. For example:
cat['size']
But it only returns 'TypeError' as I can only do with indices which I can understand.
>>> cat = ['fat', 'orange', 'loud']
>>> size, color, disposition = cat
Then, what is the purpose of this multiple assignment for lists? How can it be used after the assignment?
Sorry if my question is not clear. (Only started Python and coding a week ago...) Thank you for your time!
Upvotes: 1
Views: 53
Reputation: 4276
You are doing so called sequence unpacking
(see last paragraph):
x, y, z = t
This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires the list of variables on the left to have the same number of elements as the length of the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.
For example:
>>> t = [1, 'two', 3.0]
>>> x, y, z = t
>>> t
[1, 'two', 3.0]
>>> x
1
>>> y
'two'
>>> z
3.0
Upvotes: 2
Reputation: 848
You are assigning the variables size = 'fat'
, color = 'orange'
and so on.
Upvotes: 0