Arti
Arti

Reputation: 7762

Unpack list to variables

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]

Upvotes: 51

Views: 50692

Answers (5)

bruno desthuilliers
bruno desthuilliers

Reputation: 77892

Something like this?

>>> row = ["Title", "url", 33, "title2", "keyword"]
>>> title, url, price, title2, keyword = row

Upvotes: 92

IndPythCoder
IndPythCoder

Reputation: 753

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

Upvotes: 1

Aleksandr Tukallo
Aleksandr Tukallo

Reputation: 1427

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

Upvotes: 40

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

Upvotes: 3

ApproachingDarknessFish
ApproachingDarknessFish

Reputation: 14313

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.

Upvotes: 11

Related Questions