Appending int value to a bunch of list variables - python

I am trying to append an int value to a bunch of list variables all at once. Is there a for loop or such a function that would allow me to do that? Like I would like to append the val int to all list variables defined below.
val = 100
list_1=[]
list_2=[]
list_3=[]
list_4= []

Create a list containing all the lists, then use a loop:
val = 100
list_1 = []
list_2 = []
list_3 = []
list_4 = []
list_of_lists = [list_1, list_2, list_3, list_4]
for li in list_of_lists:
li.append(val)
Caution: do not be tempted to create list_of_lists in the following way:
list_of_lists = [[]] * 4
This will create a single list with 4 references to it, and changes done through 1 of them will be seen by all the other.
However, you can do
list_of_lists = [[] for _ in range(4)]
for li in list_of_lists:
li.append(100)
print(list_of_lists)
# [[100], [100], [100], [100]]

For something like this I would prefer a function to do so, as it is likely you'll do this again.
def appendAll(value, *args):
for listItem in args:
listItem.append(value)
This allows you to add a value to any set of lists. It doesn't require you to setup a list of variables as *args lets you pass any number of arguments and creates a tuple which lets us loop through each list and append our value to each list.
list1 = []
list2 = []
list3 = []
val = []
#now we can append val to all the lists or some of them
appendAll(val, list1, list2, list3)

Related

List combination based on value of each index in another list

I have the following two lists
list_1 = [3, 5, 7, 2]
list_2 = [
'1-CHA', '2-NOF', '3-INC',
'4-CHA', '5-NOF', '6-NOF', '7-INC', '8-INC',
'9-INC', '10-INC', '11-CHA', '12-NOF', '13-CHA', '14-CHA', '15-INC',
'16-INC', '17-INC'
]
I want to combine the two lists in the following way:
final_list = [
'1-CHA|2-NOF|3-INC',
'4-CHA|5-NOF|6-NOF|7-INC|8-INC',
'9-INC|10-INC|11-CHA|12-NOF|13-CHA|14-CHA|15-INC',
'16-INC|17-INC'
]
final_list - should have the same length as list_1
You can create an iterator from list_2 so that you can fetch items from the list for the number of times specified in list_1 by calling next on the iterator:
seq = iter(list_2)
final_list = ['|'.join(next(seq) for _ in range(n)) for n in list_1]
You can also use itertools.islice instead to avoid repeated calls to next (thanks to #gog for the suggestion):
from itertools import islice
seq = iter(list_2)
final_list = ['|'.join(islice(seq, 0, n)) for n in list_1]
To do it without using list comprehension or generator expression, you can create an empty list and append items to it:
seq = iter(list_2)
final_list = []
for n in list_1:
items = []
for _ in range(n):
items.append(next(seq))
final_list.append('|'.join(items))
Demo: https://replit.com/#blhsing/BlandEssentialJavadoc
You could do it like this:
final_list = [
# Join with a `|` pipe character
'|'.join(
# Slice list 2
list_2[
# Start at the sum of values less than i then sum of values including i
sum(list_1[:i]):sum(list_1[:i+1])])
for i in range(len(list_1))
]
On one line:
final_list = ['|'.join(list_2[sum(list_1[:i]):sum(list_1[:i+1])]) for i in range(len(list_1))]

How to create lists using for loop in Python

What I want to get is
[a][b][c]
Getting each index from an array a=[a,b,c]. I’m using this to approach a value in dictionary.
All I could find was .append() but this returns me [a,b,c] not [a][b][c]
This is the function that I made
Def loop():
Newlist = []
for i in a:
Newlist.append(i)
return Newlist
You want to append a list of one value, not a single value. i.e.
>>> new_list = []
>>> new_list.append([1])
>>> new_list.append([2])
>>> new_list.append([3])
[[1], [2], [3]]
So in the method you'd do something like this:
def loop():
new_list = []
for i in a:
new_list.append([i])
return new_list
Try this:
Create a new list inside the loop that gets reset each time, add your variable, then add the new list to the parent list.
You can also grab individual lists from the parent list using the following: Newlist[1]
Def loop():
Newlist = []
for i in a:
temp_list = []
temp_list.append(I)
Newlist.append(temp_list)
return Newlist

Append a list that’s in another list

I’m trying to append a list that’s in another list.
import random
list1 = []
list2 = []
list3 = [list1, list2]
Index = random.choice(list3)
Index = list3.index(Index)
print(Index)
list3[Index].append(“Test”)
print(list3[Index])
I want it to add “test” to either list1 or list2 depending on the value of index.
For some reason, if I repeat the process twice, and the value of index changes, “Test” is added twice to the same list. How do I accomplish this?
random.choice returns one of the items in the given list, which in this case are the references to, rather than the indices of, list1 and list2.
You should append directly to the list returned by random.choice instead:
import random
list1 = []
list2 = []
list3 = [list1, list2]
lst= random.choice(list3)
lst.append('Test')
print(list3)
This can output:
[['Test'], []]

How to merge n lists together item by item for each list

I want to make one large list for entering into a database with values from 4 different lists. I want it to be like
[[list1[0], list2[0], list3[0], list4[0]], [list1[1], list2[1], list3[1], list4[1]], etc.....]
Another issue is that currently the data is received like this:
[ [ [list1[0], list1[1], [list1[3]]], [[list2[0]]], etc.....]
I've tried looping through each list using indexs and adding them to a new list based on those but it hasn't worked, I'm pretty sure it didn't work because some of the lists are different lengths (they're not meant to be but it's automated data so sometimes there's a mistake).
Anyone know what's the best way to go about this? Thanks.
First list can be constructed using zip function as follows (for 4 lists):
list1 = [1,2,3,4]
list2 = [5,6,7,8]
list3 = [9,10,11,12]
list4 = [13,14,15,16]
res = list(zip(list1,list2,list3,list4))
For arbitrtary number of lists stored in another list u can use *-notation to unpack outer list:
lists = [...]
res = list(zip(*lists))
To construct list of lists for zipping from you data in second issue use flatten concept to it and then zip:
def flatten(l):
res = []
for el in l:
if(isinstance(el, list)):
res += flatten(el)
else:
res.append(el)
return res
auto_data = [...]
res = list(zip(*[flatten(el) for el in auto_data]))
Some clarification at the end:
zip function construct results of the smallest length between all inputs, then you need to extend data in list comprehension in last code string to be one length to not lose some info.
So if I understand correctly, this is your input:
l = [[1.1,1.2,1.3,1.4],[2.1,2.2,2.3,2.4],[3.1,3.2,3.3,3.4],[4.1,4.2,4.3,4.4]]
and you would like to have this output
[[1.1,2.1,3.1,4.1],...]
If so, this could be done by using zip
zip(*l)
Make a for loop which only gives you the counter variable. Use that variable to index the lists. Make a temporary list , fill it up with the values from the other lists. Add that list to the final one. With this you will et the desired structure.
nestedlist = []
for counter in range(0,x):
temporarylist = []
temporarylist.append(firstlist[counter])
temporarylist.append(secondlist[counter])
temporarylist.append(thirdlist[counter])
temporarylist.append(fourthlist[counter])
nestedlist.append(temporarylist)
If all the 4 lists are the same length you can use this code to make it even nicer.
nestedlist = []
for counter in range(0,len(firstlist)): #changed line
temporarylist = []
temporarylist.append(firstlist[counter])
temporarylist.append(secondlist[counter])
temporarylist.append(thirdlist[counter])
temporarylist.append(fourthlist[counter])
nestedlist.append(temporarylist)
This comprehension should work, with a little help from zip:
mylist = [i for i in zip(list1, list2, list3, list4)]
But this assumes all the list are of the same length. If that's not the case (or you're not sure of that), you can "pad" them first, to be of same length.
def padlist(some_list, desired_length, pad_with):
while len(some_list) < desired_length:
some_list.append(pad_with)
return some_list
list_of_lists = [list1, list2, list3, list4]
maxlength = len(max(list_of_lists, key=len))
list_of_lists = [padlist(l, maxlength, 0) for l in list_of_lists]
And now do the above comprehension statement, works well in my testing of it
mylist = [i for i in zip(*list_of_lists)]
If the flatten concept doesn't work, try this out:
import numpy as np
myArray = np.array([[list1[0], list2[0], list3[0], list4[0]], [list1[1], list2[1], list3[1], list4[1]]])
np.hstack(myArray)
Also that one should work:
np.concatenate(myArray, axis=1)
Just for those who will search for the solution of this problem when lists are of the same length:
def flatten(lists):
results = []
for numbers in lists:
for output in numbers:
results.append(output)
return results
print(flatten(n))

Introducing new variables using a given string

I have a list of names my_names = ["A","B","C"]
I have a function that can takes each name from a list and returns several lists of information for that name.
def my_function(name):
return list1, list2, list3
For each name list1, list2, list3 are different.
I want to write a function that wouldn't need any user input but would return a list with 3 lists inside.
def my_function():
for name in my_list:
# Part I don't know how to do
name_list = list1, list2, list3
# A_list for "A", B_list for "B", C_list for "C"
return A_list, B_list, C_list
The only thin I don't know is how to make python introduce new empty lists depending on the name in my_list
A dictionary is best, but you can have a list of lists. Just make a main list: name_list = [] then append each list to it: name_list.append(list1), etc. Then reference each list using its index, then the elements in that list with a secondary index. For example,
def my_function():
for name in my_list:
name_list = []
name_list.append(list1)
name_list.append(list2)
name_list.append(list3)
return name_list
Then if you want to access the second element in the first list from the returned function, you would do so like:
name_list[0][1]
It's hard to say more without knowing more about your problem, but this will work, it's just not optimal.
You can create a nested list with n numbers of sublists, where n is any given number of lists
n = 3
nested_list = [[]] * n
# returns [[],[],[]]
#function that takes n, n=3
def create_nested_list(n):
nested_list = [[]] * n
return nested_list
nested list = create_nested_list(n)
You can append items in the nested list's lists by indexing, for instancce nested_list[0]=["A"] will append the number "A" to the first sublist, nested_list[1]=["B"]to the second and nested_list[2]=["C"] to the third sublist, so nested_list = [["A"],["B"],["C"]]

Categories