Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partial list unpack in Python

Tags:

python

In Python, the assignment operator can unpack a list or a tuple into variables, like this:

l = (1, 2) a, b = l # Here goes auto unpack 

But I need to specify exactly the same amount of names to the left as an item count in the list to the right. But sometimes I don't know the size of the list to the right, for example, if I use split().

Example:

a, b = "length=25".split("=") # This will result in a="length" and b=25 

But the following code will lead to an error:

a, b = "DEFAULT_LENGTH".split("=") # Error, list has only one item 

Is it possible to somehow unpack the list in the example above so I can get a = "DEFAULT_LENGTH" and b equals to None or not set? A straightforward way looks kind of long:

a = b = None if "=" in string :   a, b = string.split("=") else :   a = string 
like image 256
grigoryvp Avatar asked Apr 14 '09 19:04

grigoryvp


People also ask

How do you unpack a list element in Python?

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 I unpack a list of tuples in Python?

Python uses the commas ( , ) to define a tuple, not parentheses. Unpacking tuples means assigning individual elements of a tuple to multiple variables. Use the * operator to assign remaining elements of an unpacking assignment into a list and assign it to a variable.

How do you unpack a set in Python?

Introduction. 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, * .

Can you unpack tuples in Python?

In python tuples can be unpacked using a function in function tuple is passed and in function values are unpacked into normal variable.


2 Answers

This may be of no use to you unless you're using Python 3. However, for completeness, it's worth noting that the extended tuple unpacking introduced there allows you to do things like:

>>> a, *b = "length=25".split("=") >>> a,b ("length", ['25']) >>> a, *b = "DEFAULT_LENGTH".split("=") >>> a,b ("DEFAULT_LENGTH", []) 

I.e. tuple unpacking now works similarly to how it does in argument unpacking, so you can denote "the rest of the items" with *, and get them as a (possibly empty) list.

Partition is probably the best solution for what you're doing however.

like image 181
Brian Avatar answered Oct 07 '22 02:10

Brian


# this will result in a="length" and b="25" a, b = "length=25".partition("=")[::2]  # this will result in a="DEFAULT_LENGTH" and b="" a, b = "DEFAULT_LENGTH".partition("=")[::2] 
like image 43
Chris Upchurch Avatar answered Oct 07 '22 01:10

Chris Upchurch