1

For example, if I want to assign a, b, c from l = [1,2,3,4,5], I can do

a, b, c = l[:3]

but what if l is only [1,2] (or [1] or []) ?

Is there a way to automatically set the rest of the variables to None or '' or 0 or some other default value?

I thought about extending the list with default values before assigning to match the number of variables, but just wondering if there's a better way.

cs95
  • 379,657
  • 97
  • 704
  • 746
Raksha
  • 1,572
  • 2
  • 28
  • 53

1 Answers1

5

In general, to unpack N elements into N separate variables from a list of size M where M <= N, then you can pad your list slice upto N and slice again:

l = [1,]
a, b, c =  (l[:3] + [None]*3)[:3]

a, b, c
# 1, None, None

If you fancy a clean generator-based approach, this will also work:

from itertools import islice, cycle, chain

def pad(seq, filler=None):
    yield from chain(seq, cycle([filler]))

a, b, c = islice(pad([1, ]), 3)
a, b, c
# 1, None, None
cs95
  • 379,657
  • 97
  • 704
  • 746