Eagle
Eagle

Reputation: 1197

Split list into different variables

I have a list like this:

[('love', 'yes', 'no'), ('valentine', 'no', 'yes'), ('day', 'yes','yes')]

How do I split this list into three variables where each variable holds one tuple, i.e.

var1 = ('love', 'yes', 'no')
var2 = ('valentine', 'no', 'yes')
var3 = ('day', 'yes','yes')

Upvotes: 26

Views: 57655

Answers (2)

cottontail
cottontail

Reputation: 23051

You can also use * to unpack into different variables. It's useful if you don't know how many variables to list split into or if only a few variables are needed out of a list.

lst = [('love', 'yes', 'no'), ('valentine', 'no', 'yes'), ('day', 'yes','yes')]

first, *rest = lst
first  # ('love', 'yes', 'no')
rest   # [('valentine', 'no', 'yes'), ('day', 'yes', 'yes')]

# unpack the last variable
*rest, last = lst

# unpack the first two
first, second, *rest = lst

# unpack the first three
first, second, third, *rest = lst

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121466

Assign to three names:

var1, var2, var3 = listobj

Demo:

>>> listobj = [('love', 'yes', 'no'), ('valentine', 'no', 'yes'), ('day', 'yes','yes')]
>>> var1, var2, var3 = listobj
>>> var1
('love', 'yes', 'no')
>>> var2
('valentine', 'no', 'yes')
>>> var3
('day', 'yes', 'yes')

Upvotes: 46

Related Questions