You can unpack sequences and iterables into collections of variables by using an assignment operator.

p = (4, 5)
x, y = p
x
## 4
y
## 5

For this to work, the number of variables must match the number of elements in the iterable. Unpacking works on lists, tuples, strings, dictionaries, iterators, generators, files, and more data types.

data = ["BIGINC", 50, 355.6, (2019, 5, 12)]
name, shares, price, date = data
name
## 'BIGINC'
shares
## 50
price
## 355.6
date
## (2019, 5, 12)

You can also discard certain unpacked values that you might not want to use. You can achieve this by using throwaway variable names, the convention is to use an underscore _.

data = ["BIGINC", 50, 355.6, (2019, 5, 12)]
_, shares, price, _ = data

If you want to unpack less variables than the elements in the iterable, and avoid the “too many values to unpack” error, use the * (asterisk or star) expression. It will group the respective values into a list.

record = ("JoJo", "[email protected]", "773-555-1212", "847-555-1212")
name, email, *phones = record
name
## 'JoJo'
email
## '[email protected]'
phones
## ['773-555-1212', '847-555-1212']

You can place the starred variable wherever you want. At the beginning,

*trailing, current = [10, 8, 34, 56, 6]
trailing
## [10, 8, 34, 56]
current
## 6

or in the middle.

beginning, *middle, end = ["hello", 34, 45, 43, "zoo"]
beginning
## 'hello'
middle
## [34, 45, 43]
end
## 'zoo'

Unpacking can be useful in combination with some string processing, such as splitting.

line = "jojo:*:-2:Default User:/var/empty:/usr/bin/false"
uname, *fields, homedir, shell = line.split(":")
uname
## 'jojo'
homedir
## '/var/empty'
shell
## '/usr/bin/false'
fields
## ['*', '-2', 'Default User']

Of course, you can unpack and throw away variables.

data = ["BIGINC", 50, 355.6, (2019, 5, 12)]
name, *_, (*_, year) = data
name
## 'BIGINC'
year
## 12