Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpack list to variables

Tags:

python

list

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] 
like image 932
Arti Avatar asked Dec 16 '15 09:12

Arti


People also ask

How do you convert a list into a variable?

Method #1 : Using "=" operator This task can be performed using a “=” operator. In this we just ensure enough variables as the count of list elements and assign them to list, the list elements get allotted to variables in order of their assignment.

How do I unpack a list element?

Summary. Unpacking assigns elements of the list to multiple variables. Use the asterisk (*) in front of a variable like this *variable_name to pack the leftover elements of a list into another list.

How do you unpack an array in Python?

To unpack elements of a uint8 array into a binary-valued output array, use the numpy. unpackbits() method in Python Numpy. The result is binary-valued (0 or 1). The axis is the dimension over which bit-unpacking is done.

What does it mean to unpack a list in Python?

Unpacking in Python refers to an operation that consists of assigning an iterable of values to a tuple (or list ) of variables in a single assignment statement. As a complement, the term packing can be used when we collect several values in a single variable using the iterable unpacking operator, * .


2 Answers

Something like this?

>>> row = ["Title", "url", 33, "title2", "keyword"] >>> title, url, price, title2, keyword = row 
like image 97
bruno desthuilliers Avatar answered Sep 20 '22 15:09

bruno desthuilliers


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

like image 41
Aleksandr Tukallo Avatar answered Sep 17 '22 15:09

Aleksandr Tukallo