Unpacking A List Into Variables

You know that you can create a list from individual variables

x = 1
y = 2
z = 3

a = [x, y, z]


But what if have a list and you want to unpack it into separate variables? You might use subscripts to extract the individual values

a = [1, 2, 3]
x = a[0]
y = a[1]
z = a[2]

Or, with a multiple assignment statement

x, y, z = a[0], a[1], a[2]

But there is an easier way. Python can unpack a list into a series of variables like this

x, y, z = a

However, there is one requirement: the number of list items must match the number of variables. You are not allowed to have extra variables or unused list items.




Throwing away don't care values


You can use a single underscore as a placeholder variable. This can be useful when Python's syntax requires a variable but you're never going to use it.

a = [1, 2, 3, 4, 5]
first, _, _, _, last = a

Python 3.x supports wildcards

Python 3.x supports wildcards in the form of starred variables
  • There can be only one starred variable.
  • The starred variable is only used if the number of list items is greater than the number of unstarred variables.
  • The list values that could not be assigned to unstarred variables are collected into a list and this list is assigned to the starred variable.


No comments:

Post a Comment