List items to different variables

I get a list that is of different length, in example below, 4 or 2 items, I want to save in different variables for later handling. (I use other objects. Both snip below solve the problem, but is there a more pythonic way to do this?

my_list = [4,6,2,11]
my_list = [7,19]

# sample 1

try:
   i1 = my_list[0]
   i2 = my_list[1]
   i3 = my_list[2]
   i4 = my_list[3]
except:
   pass
# sample 2

list_len = len(my_list)

if list_len > 0: i1 = my_list[0]
if list_len > 1: i2 = my_list[1]
if list_len > 2: i3 = my_list[2]
if list_len > 3: i4 = my_list[3]

# sample 3

# how do it nice in python?

What’s the advantage of using i3 over my_list[2]?

My recommendation would be to not do that in the first place and just use the index.

later in code i3 object may be used (in code someone else wrote). with this setup, then I can check if i3 object exists etc. But good point, when bringing problem isolated, it don’t make much sense.

I would say later in code the i3 name may be used. The object either exists or it doesn’t.

As such, at the interface to such code, you could assign to the name at that time. What would you expect to do in that section if the list were only 2 items long? If it’s going to throw an error anyway, you could just throw it earlier by doing:

i1, i2, i3, i4 = my_list[:4]

Or is it somehow checking if i3 is assigned (which it wouldn’t be in the above examples)?

exec() takes a string and executes it as line of code. It is an ugly duckling but is a beautiful problem solver when there is no better way. Explained HERE.

for varidx, item in enumerate(my_list):
    exec('i'+str(varidx+1)+ '= item') #on first pass, executes 'i1 = item'

A small note here. An empty list will evaluate to a boolean False. Non-empty == True.

if list_len > 0: i1 = my_list[0]  #these give
if my_list: i1 = my_list[0]       #the same result

This boolean behavior is a bit hidden, though, and only readable by someone experienced enough to know about it.

1 Like

There are many ways to do this, and the choice between them is mostly a matter of personal taste. But if you absolutely know that the list must have exactly 2 or 4 items, you can do this:

i1, i2 = mylist[:2]
i3, i4 = mylist[2:] or [None, None]  # Use None as default for missing values

Alternatively:

i1, i2, *tmp = mylist
i3, i4 = tmp or [None, None]

One more:

i1, i2, i3, i4 = (mylist + [None, None])[:4]
2 Likes

i1, i2, *tmp = mylist
i3, i4 = tmp or [None, None]

This one suits my taste for being concise and readable with minimal mental gymnastics. The exec() loop has the benefit of parsing a data object with any number of members/elements but can be somewhat esoteric at first glance. The way Python offers you so many choices is wonderful.

1 Like