Reputation: 1197
This post follows my previous question from here: Split list into different variables
I realized that I would have multiple chunks of elements in a list and these may not always be restricted to 3. For example, I could have:
[('love', 'yes', 'no'), ('valentine', 'no', 'yes'), ('day', 'yes','yes'),
('house', 'yes','no'), ('car', 'yes','yes')]
[('love', 'yes', 'no'), ('valentine', 'no', 'yes'), ('day', 'yes','yes'),
('house', 'yes','no'), ('car', 'yes','yes'), ('balloon', 'no','no'),
('roses', 'yes','yes')]
var1, var2, var3 = listobj
works fine for only three of these element chunks. But for more, in general, how would I store all these chunks of elements into different variables?
Upvotes: 0
Views: 234
Reputation: 72261
If the length of listobj
is indeterminate, use it directly as a list instead of unpacking it into variables.
Unpacking a list of different sizes doesn't make any sense. Assume you could dynamically unpack listobj
into as many variables as possible (like var1, var2, var3... as long as needed). How would you write code that consumes these variables? You'd suddenly need to know their number and some clever way to index a particular one, or loop over them. And guess what- this is exactly why you have lists in the first place.
Upvotes: 0
Reputation: 34017
The variables are declared explicitly in your code, so the numbers of variables you could use is definite, there is no way to unpack a tuple(or list) with unknown length to definite numbers of vars. But you can use *
to make extended iterable unpacking in python3:
>>> a, *b, c = range(5)
>>> a
0
>>> c
4
>>> b
[1, 2, 3]
Upvotes: 4