42

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
  • 20,142
  • 17
  • 60
  • 81
Arti
  • 6,685
  • 11
  • 49
  • 111

5 Answers5

69

Something like this?

>>> row = ["Title", "url", 33, "title2", "keyword"]
>>> title, url, price, title2, keyword = row
ggorlen
  • 33,459
  • 6
  • 59
  • 67
bruno desthuilliers
  • 72,252
  • 6
  • 79
  • 103
24

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,119
  • 14
  • 20
  • 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
  • 13,641
  • 7
  • 39
  • 77
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
0

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
  • 526
  • 5
  • 10