Python append adds an item to every variable - python

I'm iterating on a list and attempting to create sublists from its items. Every time I append to a variable, the value is added to every other variable that I have defined. I've stripped down the code substantially to illustrate.
item = 'things.separated.by.periods'.split('.')
list1 = list2 = []
i = item.pop(0)
print i
list1.append(i)
i = item.pop(0)
print i
list2.append(i)
print(item, list1, list2)
Returns:
things
separated
(['by', 'periods'], ['things', 'separated'], ['things', 'separated'])
What I expected:
things
separated
(['by', 'periods'], ['things'], ['separated'])
I think this might by answered here, but I'm not sure how to apply this fix to my circumstances. Thanks in advance!

The problem is the line
list1 = list2 = []
This makes list1 and list2 refer to the exact same list, so that if you append an item to one you also append it to the other. Change it to
list1 = []
list2 = []

list1 = list2 = []
You are setting list1 to be the exact same list as list2. Therefore, they basically mean the same thing.
To fix this, try something like this:
list1, list2 = [], []

Related

sort string list by another string list python

5 downvotes for what? like seriously wtf?
I asked a clear question and got a clear answer from Barmer.
Now i cant ask another question and now im forced to create a new stack overflow account and dont suggest that i dont cause your system is shit so yes i 100% absolutely will create a new one. and another one, and another one.
Eat shit.
So i have 2 lists.
list1 is the list of which order im trying to recreate.
list2 is the unordered list.
How to arrange list2 in same order as list1?
List1
list1 = [
"loaded_sound,sfx/weapon/smg/type100/fire",
"loaded_sound,sfx/weapon/smg/type100/foley",
"loaded_sound,sfx/weapon/special/bouncing_betty",
"loaded_sound,sfx/weapon/special/flame_thrower/foley",
"loaded_sound,sfx/weapon/special/molotov",
"loaded_sound,sfx/weapon/special/ptrs/fire",
"loaded_sound,sfx/weapon/special/satchel_charge",
"loaded_sound,sfx/weapon/tank/kingtiger/fire",
"loaded_sound,sfx/weapon/tank/ringoffs",
"loaded_sound,sfx/weapon/tank/sherman/fire",
"loaded_sound,sfx/weapon/tank/tank_reload/foley",
"loaded_sound,sfx/weapon/tank/tank_reload",
"loaded_sound,sfx/weapon/tesla/bounce",
"loaded_sound,sfx/weapon/tesla",
"loaded_sound,sfx/weapon/uber",
"loaded_sound,stream/music/mission/zombie",
"loaded_sound,voiceovers/zombie/ann",
"loaded_sound,voiceovers/zombie/monkey/explo_vox",
"loaded_sound,voiceovers/zombie/monkey/groan",
"loaded_sound,voiceovers/zombie/monkey",
"loaded_sound,voiceovers/zombie/monkey/raise_vox",
"loaded_sound,voiceovers/zombie/pa"
]
List2:
list2 = [
"loaded_sound,sfx/weapon/smg/type100/fire",
"loaded_sound,voiceovers/zombie/pa",
"loaded_sound,sfx/weapon/smg/type100/foley",
"loaded_sound,voiceovers/zombie/monkey/raise_vox",
"loaded_sound,sfx/weapon/special/bouncing_betty",
"loaded_sound,sfx/weapon/special/flame_thrower/foley",
"loaded_sound,voiceovers/zombie/monkey",
"loaded_sound,voiceovers/zombie/monkey/groan",
"loaded_sound,sfx/weapon/special/molotov",
"loaded_sound,voiceovers/zombie/monkey/explo_vox",
"loaded_sound,sfx/weapon/special/ptrs/fire",
"loaded_sound,voiceovers/zombie/ann",
"loaded_sound,sfx/weapon/special/satchel_charge",
"loaded_sound,stream/music/mission/zombie",
"loaded_sound,sfx/weapon/tank/kingtiger/fire",
"loaded_sound,sfx/weapon/uber",
"loaded_sound,sfx/weapon/tank/ringoffs",
"loaded_sound,sfx/weapon/tesla",
"loaded_sound,sfx/weapon/tank/sherman/fire",
"loaded_sound,sfx/weapon/tesla/bounce",
"loaded_sound,sfx/weapon/tank/tank_reload/foley",
"loaded_sound,sfx/weapon/tank/tank_reload",
]
What ive tried:
_newList = []
# sort list2 in same order as list 1
for i in list1:
_line_ = i
for j in list2:
if j == _line_:
_newList.append(j)
But all this did was recreate list2 as it is. it didnt rearrange anything.
You can use the index in list1 as the key when sorting list2.
If the lists are long, it would be good to create a dictionary that returns the indexes, rather than searching for each.
list1_dict = {val: i for i, val in enumerate(list1)}
list2.sort(key = lambda x: list1_dict.get(x, -1))
If there are any elements in list2 that aren't in list1, this will sort them to the beginning.
I suggest you the following one-line style code:
list2 = [i for i in list1 if i in list2]

How to return all item in list of lists that are not in other list of lists in Python?

I have 2 list of lists:
list1: [[1,2,3],[2,5],[6,7,4]]
list2: [[1,3],[2],[6,4],[9,0,3]]
I want to do few things:
Find every number that is in list 1 but is not in list 2, store it in a new list, and then append this new list to list2.
In our case: new_list = [5,7]
and then, we will add it to list2 = [[1,3],[2],[6,4],[9,0,3],[5,7]]
Then, I want to remove duplicates of numbers from each list1 and list 2:
In our case: list1 = [[1,3],[2,5],[6,7,4]], list2 = [[1],[2],[6,4],[9,0,3],[5,7]]
I have an implementation using For loops, but I need something more elegant for that.
Can you help me please find out a way?
Using Python, you can do the first part with a set comprehension:
list2.append(list({i for j in list1 for i in j}.difference({i for j in list2 for i in j})))

Python trouble with matching tuples

For reference this is my code:
list1 = [('10.180.13.101', '10.50.60.30', 'STCMGMTUNIX01')]
list2 = [('0.0.0.0', 'STCMGMTUNIX01')]
for i in list1:
for j in list2:
for k in j:
print (k)
if k.upper() in i:
matching_app.add(j)
for i in matching_app:
print (i)
When I run it, it does not match. This list can contain two or three variables and I need it to add it to the matching_app set if ANY value from list2 = ANY value from list1. It does not work unless the tuples are of equal length.
Any direction to how to resolve this logic error will be appreciated.
You can solve this in a few different ways. Here are two approaches:
Looping:
list1 = [('10.180.13.101', '10.50.60.30', 'STCMGMTUNIX01')]
list2 = [('0.0.0.0', 'STCMGMTUNIX01')]
matches = []
for i in list1[0]:
if i in list2[0]:
matches.append(i)
print(matches)
#['STCMGMTUNIX01']
List Comp with a set
merged = list(list1[0] + list2[0])
matches2 = set([i for i in merged if merged.count(i) > 1])
print(matches2)
#{'STCMGMTUNIX01'}
I'm not clear of what you want to do. You have two lists, each containing exactly one tuple. There also seems to be one missing comma in the first tuple.
For finding an item from a list in another list you can:
list1 = ['10.180.13.101', '10.50.60.30', 'STCMGMTUNIX01']
list2 = ['0.0.0.0', 'STCMGMTUNIX01']
for item in list2:
if item.upper() in list1: # Check if item is in list
print(item, 'found in', list1)
Works the same way with tuples.

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

Categories