26

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')
cottontail
  • 10,268
  • 18
  • 50
  • 51
Eagle
  • 1,187
  • 5
  • 22
  • 40

2 Answers2

46

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')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

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
cottontail
  • 10,268
  • 18
  • 50
  • 51