You have given a list. Length of list can vary.
As an example:
1. ll = [1,2,3]
2. ll = [1,2,3,4]
3. ll = [1,2]
4. ll = []
I want to store value in three variables,
var1,var2,var3 = None,None,None
If ll[0] exists then var1 = ll[0]
If ll[1] exists then var2 = ll[1]
If ll[3] exists then var3 = ll[2]
I have written the solution but it contains if else. Code I have written:-
var1,var2,var3 = None,None,None
if len(ll) == 1:
var1,var2,var3 = ll[0],None,None
elif len(ll) == 2:
var1,var2,var3 = ll[0],ll[1],None
else:
var1,var2,var3 = ll[0],ll[1],ll[2]
Probably the simplest one
var1, var2, var3 = (ll + [None] * 3)[:3]
You can use unpacking:
ll = [1,2,3]
var1, var2, var3 = (ll + [None]*len(ll))[:3]
print var1
# 1
print var2
# 2
print var3
# 3
ll = [1,2]
var1, var2, var3 = (ll + [None]*len(ll))[:3]
print var1
# 1
print var2
# 2
print var3
# None
The ll + [None]*len(ll)
adds (or removes) to the current list by adding [None, etc]
. The amount of None
s depends on the length of the list.
So for example, if the list was [1]
, it would add [None, None]
to that list, therefore the unpacking wouldn't raise an error as there is the same amount of elements.
You're probably better off using a conditional, maybe something like:
if len(ll) > 3:
var1, var2, var3 = ll[:3]
else:
var1, var2, var3 = ll + [None] * (3-len(ll))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With