Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to assign a default value when unpacking?

I have the following:

>>> myString = "has spaces"
>>> first, second = myString.split()
>>> myString = "doesNotHaveSpaces"
>>> first, second = myString.split()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack

I would like to have second default to None if the string does not have any white space. I currently have the following, but am wondering if it can be done in one line:

splitted = myString.split(maxsplit=1)
first = splitted[0]
second = splitted[1:] or None
like image 962
neverendingqs Avatar asked Jul 29 '16 19:07

neverendingqs


People also ask

How do you assign default values to variables?

An assignment of the form variable=${value:-default} assigns value to $variable if it is set: otherwise it assigns default to $variable. In the example above, the variable ${PAGER:-more} is expanded to either the value of $PAGER, or if this is not set, to more.

What is unpacking in programming?

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

What is packing and unpacking?

Iterable unpacking refers to the action of assigning an iterable of values to a tuple or list of identifiers within a single assignment; Iterable packing refers to the action of capturing several values into one identifier in a single assignment.


2 Answers

May I suggest you to consider using a different method, i.e. partition instead of split:

>>> myString = "has spaces"
>>> left, separator, right = myString.partition(' ')
>>> left
'has'
>>> myString = "doesNotHaveSpaces"
>>> left, separator, right = myString.partition(' ')
>>> left
'doesNotHaveSpaces'

If you are on python3, you have this option available:

>>> myString = "doesNotHaveSpaces"
>>> first, *rest = myString.split()
>>> first
'doesNotHaveSpaces'
>>> rest
[]
like image 195
wim Avatar answered Sep 17 '22 20:09

wim


A general solution would be to chain your iterable with a repeat of None values and then use an islice of the result:

from itertools import chain, islice, repeat

none_repat = repeat(None)
example_iter = iter(range(1)) #or range(2) or range(0)

first, second = islice(chain(example_iter, none_repeat), 2)

this would fill in missing values with None, if you need this kind of functionality a lot you can put it into a function like this:

def fill_iter(it, size, fill_value=None):
    return islice(chain(it, repeat(fill_value)), size)

Although the most common use is by far for strings which is why str.partition exists.

like image 27
Tadhg McDonald-Jensen Avatar answered Sep 18 '22 20:09

Tadhg McDonald-Jensen