Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List manipulation in python

Tags:

python

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]

Is there any good method to solve this without using IF/Else.

like image 962
Anurag Avatar asked Dec 09 '22 11:12

Anurag


2 Answers

Probably the simplest one

var1, var2, var3 = (ll + [None] * 3)[:3]
like image 173
evhen14 Avatar answered Dec 31 '22 12:12

evhen14


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 Nones 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))
like image 40
TerryA Avatar answered Dec 31 '22 12:12

TerryA