Anurag
Anurag

Reputation: 1013

List manipulation in 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.

Upvotes: 4

Views: 1071

Answers (6)

bruno desthuilliers
bruno desthuilliers

Reputation: 77892

Since we don't have an itertools based solution so far:

import itertools as it
var1, var2, var3 = list(it.chain(ll, it.repeat(None, 3- len(ll))))[:3]

But that's just ridiculous

Upvotes: 0

Jon Clements
Jon Clements

Reputation: 142136

I'd go and extend this to allow arbitrary iterables instead of depending on being able to slice, eg:

from itertools import chain, repeat, islice
a, b, c = islice(chain(your_iterable, repeat(None)), 3)

Although, if I didn't want to unpack as such, then I'd look at using a dict but this'd have slightly different semantics:

var = dict(enumerate(islice(your_iterable, 3), start=1))
var[1] # first item (think of it as `var1`) or
var.get(1) # but get `None` if it wasn't "unpacked"

Upvotes: 1

user278064
user278064

Reputation: 10170

Even if I don't encourage this:

var1, var2, var3 = ll[:3] + [None] * (3-min(3, len(ll)))

Basically it pads the missing values with a list of None.

Upvotes: 0

evhen14
evhen14

Reputation: 1927

Probably the simplest one

var1, var2, var3 = (ll + [None] * 3)[:3]

Upvotes: 12

TerryA
TerryA

Reputation: 59974

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))

Upvotes: 1

OdraEncoded
OdraEncoded

Reputation: 3134

Try this snippet

# You can use other values for this list
default_list = [None] * 3 # Same as None, None, None
var1, var2, var3 = ll[:len(default_list)] + default_list[len(ll):]

Basically what it does is create a list the same size of default_list filling any missing indexes with the values in default_list.

Upvotes: 0

Related Questions