Home > Back-end >  Assign values to multiple variables
Assign values to multiple variables

Time:03-04

In python we can

a,b = tuple_with_two_items
a,b,c = tuple_with_three_items

Can we have something like

a,b,c = tuple_with_two_or_three_items

, so that when there are 3 items in the tuple, all a,b,c have values, while when there are only 2 items, c will take None?

CodePudding user response:

This would give you None for c:

a, b, c, *_ = *tuple_with_two_or_three_items, None

Or with Python 3.10:

match tuple_with_two_or_three_items:
    case a, b, c:
        pass
    case a, b:
        c = None

CodePudding user response:

The closest would be:

a, b, *c = tuple_with_two_or_three_items

c will be a list of all the items after the first 2. If there are only 2 items, c will be empty, otherwise it will be contain the third value (and more if there are more than 3).

CodePudding user response:

You could write a function to pad the size of a tuple:

def pad_tuple(items, n, fill=None):
    if len(items) < n:
        return items   (fill,)*(n-len(items))
    return items

Then use it like this:

a, b, c = pad_tuple(tuple_with_two_or_three_items, 3)

(but an if-statement would probably be easier)

  • Related