Reputation: 111
I have a string from user. It must containt a comma to split by it and assign to variables. But what if user miss a comma? Surely I can check len of splitted string in if-else branches, but maybe there is another way, I mean assignment during list has a values. For example
a, b, c, d, e = list(range(3)) # 'a' and 'b' are None or not exists
Upvotes: 0
Views: 76
Reputation: 612
You could do something like this:
>>> alist=list(range(3))
>>> alist
[0, 1, 2]
>>> a,b,c,*d=alist
>>> a,b,c
(0, 1, 2)
>>> d
[]
If there are no more elements, d
is an empty list. It uses the unpacking operator *
. Not the best possible solution for large lists, so I would still define a function for that. For small cases, it works well. (You could assume that is d==[]
, there are no more elements in alist
)For example, you could add:
return False if not d else return True
Upvotes: 1
Reputation: 2845
You are free to extend the list with None values before extraction.
li = list(range(3))
expected_size = 5
missing_size = expected_size - len(li)
none_li = [None] * missing_size
new_li = li + none_li
a, b, c, d, e = new_li
Upvotes: 0