47

I have a list:

row = ["Title", "url", 33, "title2", "keyword"]

Is there a more pythonic way to unpack this values like:

title, url, price, title2, keyword = row[0], row[1], row[2], row[3], row[4]
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Arti
  • 7,356
  • 12
  • 57
  • 122

5 Answers5

78

Something like this?

>>> row = ["Title", "url", 33, "title2", "keyword"]
>>> title, url, price, title2, keyword = row
ggorlen
  • 44,755
  • 7
  • 76
  • 106
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
31

Also if you need only few first variables, in Python 3 you can use:

row = ["Title", "url", 33, "title2", "keyword"]
title, url, *_ = row

It's a nice way to extract few first values without using explicit indices

Aleksandr Tukallo
  • 1,299
  • 17
  • 22
  • could you please advice the pythonic way how to extract **last** value explicitly? – Madness Apr 01 '21 at 09:28
  • @Madness I don't know how to extract both few first values and few last values, but you can extract last values only by applying reverse to the list and then using the above-mentioned syntax – Aleksandr Tukallo Apr 08 '21 at 10:04
  • 1
    @Madness how about `*_, last = row` or `last = row[-1]`? – ggorlen Nov 28 '21 at 15:30
11

In fact, python automatically unpacks containers when variables are separated by commas. This assigns each element in row to the variables on the left:

title, url, price, title2, keyword = row

After this assignment, title has the value of "Title", price has the value of 33, etc.

ApproachingDarknessFish
  • 14,133
  • 7
  • 40
  • 79
3

You could also unpack it easily to a class or namedtuple:

from collections import namedtuple

row = ["Title", "url", 33, "title2", "keyword"]

Entry = namedtuple("Entry", "title url price title2 keyword")
new_entry  = Entry(*row)
print(new_entry.title) # Title
1

Another way simple tuple/list packing - Note ',' after *row

*row, = ["Title", "url", 33, "title2", "keyword"]  # creates a tuple of row elements
title, url, price, title2, keyword = row  # list unpacking unpacked here
for i in range(len(row)):
    print(row[i])
print()
print(title)
Title
url
33
title2
keyword

Title
IndPythCoder
  • 693
  • 6
  • 10