Unpack list to variables

Question:

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]
Asked By: Arti

||

Answers:

Something like this?

>>> row = ["Title", "url", 33, "title2", "keyword"]
>>> title, url, price, title2, keyword = row
Answered By: bruno desthuilliers

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.

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

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

Answered By: Aleksandr Tukallo

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
Answered By: IndPythCoder
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.