Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending multiple returned values to different lists in Python

I have function that calculates and returns 7 floats, and each value gets appended to a different list. I feel there must be something wrong if I am typing out 7 different append statements, but is there a more pythonic way todo this.

For example (I don't even like typing it here!):

a,b,c,d,e,f,g = range(7)
alist.append(a)
blist.append(b)
clist.append(c)
dlist.append(d)
elist.append(e)
flist.append(f)
glist.append(g)

According to this related question it would seem this is not possible... There must be a way using +=[a] or list comprehension or a loop or something?

One thing that comes to mind is to keep appending all those 7 values to a master list and then transpose it at the end with zip(*MasterList) to generate the individual lists?

What would people recommend?

like image 684
beroe Avatar asked Apr 30 '14 23:04

beroe


People also ask

How to append multiple items to a list in Python?

In today's tutorial, we'll learn how to append multiple items to a list. 1. Using the append () method 2. Using '+' operator 3. Using extend () method 4. Real example 1. Using the append () method The append () method adds a single element to an existing list. 1. iterate over the elements list.

Can you return multiple values from a function in Python?

Similar to returning multiple values using tuples, as shown in the previous examples, we can return multiple values from a Python function using lists. One of the big differences between Python sets and lists is that lists are mutable in Python, meaning that they can be changed.

What does append () method do in Python?

The append () method in python will add a single item to the existing list. It does not return a new list of items. However, it will modify the original list when it adds the item to the end of the list.

How to append [Python] to my_list?

So, in the above code, we try to append ["PYTHON", "PHP"] to my_list by: 1. iterate over ["PYTHON", "PHP"]. 2. append element to my_list using the append () method.


1 Answers

appenders = range(7)
mylists = [alist, blist, clist, dlist, elist, flist, glist]
for x, lst in zip(appenders, mylists):
    lst.append(x)
like image 158
Ryne Everett Avatar answered Sep 26 '22 18:09

Ryne Everett