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]

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Something like this?

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

Method 2

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

Method 3

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.

Method 4

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

Method 5

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x