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?
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.
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.
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.
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.
appenders = range(7)
mylists = [alist, blist, clist, dlist, elist, flist, glist]
for x, lst in zip(appenders, mylists):
lst.append(x)
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