How to unpack optional items from a tuple?

xorsyst

I have a list of some input values, of which the first couple of mandatory and the last couple optional. Is there any easy way to use tuple unpacking to assign these to variables, getting None if the optional parameters are missing.

eg.

a = [1,2]   
foo, bar, baz = a
# baz == None

ideally a could be any length - including longer than 3 (other items thrown away).

At the moment I'm using zip with a list of parameter names to get a dictionary:

items = dict(zip(('foo', 'bar', 'baz'), a))
foo = items.get('foo', None)
bar = items.get('bar', None)
baz = items.get('baz', None)

but it's a bit long-winded.

xorsyst

From the linked question, this works:

foo, bar, baz == (list(a) + [None]*3)[:3]

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to unpack items from a List?

From Dev

Remove all optional items from a Tuple type

From Java

How to unpack a tuple from left to right?

From Dev

How to unpack a tuple right from out parameter?

From Dev

How to unpack and print a tuple

From Dev

How to unpack a tuple returned from a function and assign it to the columns of the DataFrame?

From Dev

How to unpack std::tuple from C++ template?

From Dev

How to unpack an object as it was a tuple in a for loop?

From Dev

How to correctly unpack tuple and display it?

From Dev

How to unpack tuple with unknown size?

From Dev

How can I print items from a tuple?

From Dev

How do I access items of a dictionary using items from a tuple?

From Dev

How to unpack tuple in arguments with sugar in Nim?

From Dev

How to unpack the type of elements in tuple in dotty?

From Dev

How do I unpack tuple format in R?

From Dev

How to access tuple items?

From Dev

Unpack parts of a tuple into tuple

From Dev

How to unpack a tuple into more values than the tuple has?

From Dev

Haskell - How to take n items from a tuple list after sorting

From Dev

How to remove all the items from an array in an Optional Java Object?

From Dev

How to unpack pair of indexes of list items

From Dev

Unpack return value from length-1 tuple

From Dev

how to iterate over tuple items

From Dev

How to unpack values from a file

From Dev

How to make a tuple from a tuple?

From Dev

How to unpack a list of tuple in various length in a panda dataframe?

From Dev

How to overwrite `savefig` method so that it can unpack a tuple

From Dev

How can I unpack tuple when other variables are needed?

From Java

How to unpack tuple of length n to m<n variables

Related Related

HotTag

Archive