Unpack Variable List

I have a list:

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

Is there a more pythonic way to unpack these values, for example:

 title, url, price, title2, keyword = row[0], row[1], row[2], row[3], row[4] 
+12
source share
4 answers

Something like that?

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

Also for the record, note that your example ends with an IndexError (Python lists are zero-based).

EDIT: The above note was written before the OP example was installed ...

+24
source

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

 title, url, price, title2, keyword = row 

After this assignment, title has the value “Heading”, price has a value of 33, etc.

+6
source

You can also easily unzip it into 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
source

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

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

This is a good way to extract the first few values ​​without using explicit indexes.

0
source

Source: https://habr.com/ru/post/1238357/


All Articles