Append is overwriting existing data in list
You can use slice stack = stack[:] + [element["a"]]
instead of append
method of list:
var_gobal = []
def parse(list_parse,stack):
global var_gobal
for element in list_parse:
stack = stack[:] + [element["a"]]
print(stack)
var_gobal.append(stack)
to_parse = [{"a":"abc","b":"bcd","c":"cde"},{"a":"def","b":"efg","c":"ghi"}]
parse(to_parse,[])
print (var_gobal)
Output:
['abc']
['abc', 'def']
[['abc'], ['abc', 'def']]
Or, using stack = stack + [element["a"]]
would give same result as well.
To see the difference, we can see following example:
my_list = ['a', 'b']
tmp = []
global_var = []
for i in my_list:
tmp.append(i)
global_var.append(tmp)
global_var
This outputs global_var
as [['a', 'b'], ['a', 'b']]
.
Although, tmp
is appended to global_var
in every iteration through my_list
, on every append all referencing (or all that are pointing) to tmp
is changed. Instead if slice
or +
is used, new list is created with all the elements in first since [:]
is used:
my_list = ['a', 'b']
tmp = []
global_var = []
for i in my_list:
tmp = tmp[:] + [i]
global_var.append(tmp)
global_var
This results: [['a'], ['a', 'b']]
List append is overwriting my previous values
You are appending the same dictionary to your list each time. The reference is to one dictionary only. You can reference a new dictionary by constructing a new dictionary each time:
for term in query_string.split():
term_string = {}
term_string['term'] = {}
term_string['term']["labels.Name"] = ""
term_string['term']["labels.Name"] = term
must_string.append(term_string)
For construction of a nested dictionary, I recommend you utilize collections.defaultdict
: see defaultdict of defaultdict, nested.
Append method overwrites previous values in a loop
I cleaned up your code so it would be easier for both you and other people, in the future, to read. I also fixed your sorting algorithm. I saw that you were trying to implement bubble sort but you need two loops for that. I added that in so now you should be sorting correctly and you should be able to print out each step of the sort.
import random
import matplotlib.pyplot as plt
import numpy as np
if __name__ == '__main__' :
mylist = [*range(1, 5)]
random.shuffle(mylist)
liste1 = mylist
a = liste1
print("Before:", a)
b = list()
c = list()
print("===========================")
for i in range(len(a) -1):
for j in range(len(a) - i - 1):
if(a[j] > a[j + 1]):
temp = a[j]
a[j] = a[j + 1]
a[j + 1] = temp
b.append(a[:]) # The [:] is VERY important
print(b)
print("===========================")
print("Final:", b)
liste2 = b
x = np.array(liste1)
plt.ion()
for t in liste2 :
plt.clf()
c = np.array(liste1)
plt.plot(x, c)
plt.pause(1)
plt.show()
why my appended list is overwriting I mean the previous appended element is changing?Can I know why
Since the lists are mutable...The values of the list changes everytime when you append a new value.So copy()
function will help you to copy the list.Thus no modification occurs..This code will help you...
def func(n):
m_lst=[]
lst=[]
print(m_lst)
m_lst.append(lst.copy())
print(m_lst)
for i in range(1,n+1):
lst.append(i)
m_lst.append(lst.copy())
print(m_lst)
func(4)
Output:
[]
[[]]
[[], [1]]
[[], [1], [1, 2]]
[[], [1], [1, 2], [1, 2, 3]]
[[], [1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]
Why does append overwrite the list?
Indeed your code does not work, and it is due to the line SL[:] = []
: it changes the content of the list referenced by SL
. By doing this, you change all the elements of L
, because you always append the list referenced by SL
to L
in the loop. Replacing with SL = []
will fix the problem, because in this case you create a new list without overwriting the previous one.
It could be fixed, and also be more readable and easier to debug (if needed) with the following suggestion:
L = []
for i in range(0, x + 1):
for j in range(0, y + 1):
for k in range(0, z + 1):
if i + j != n and i + k != n and k + j != n and i + j + k != n:
L.append([i, j, k])
print(L)
With x=1, y=2, z=3, n=4: it gives me the following output:
[[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 1, 0], [0, 1, 1], [0, 1, 2], [0, 2, 0],
[0, 2, 1], [0, 2, 3], [1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0], [1, 1, 1], [1, 2, 0]]
appending to a list in while loop without overwriting the list
I think you need
record.append(state.copy())
try changing your code to
import random
random.seed(100)
f = random.randint(0,3)
m = random.randint(0,3)
s = random.randint(0,3)
seq = [0.2]*s + [0.5]*m + [0.8]*f
print(seq)
random.shuffle(seq)
state = [0]*len(seq)
record = []
count = 0
while count < len(seq):
if count == 0 and random.random() < seq[count]:
state[count]+=1
record.append(state.copy())
count += 1
elif count == 0 and random.random() > seq[count]:
state[count]+=0
record.append(state.copy())
count += 0
elif count > 0 and random.random() < seq[count]:
state[count]+=1
state[count-1]-=1
record.append(state.copy())
count += 1
elif count > 0 and random.random() > seq[count]:
state[count]+=0
state[count-1]-=0
record.append(state.copy())
count += 0
print(record)
My output
[[1, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 1]]
Hopefully this example makes it clear
a = []
b = [4,5,6]
a.append(b)
b[1] = 2
print(a)
this will output
[[4, 2, 6]]
and not
[[4, 5, 6]]
because the append is maintaining a reference to the list b
Related Topics
Python Multiprocessing Pool Hangs At Join
Loading All Images Using Imread from a Given Folder
Get All Rows That Have Same Value in Pandas
Convert a Standard Python Key Value Dictionary List to Pyspark Data Frame
Get the Last Sunday and Saturday'S Date in Python
Pandas: Calculate the Percentage Between Two Rows and Add the Value as a Column
Get First Date and Last Date of Current Quarter in Python
How to Skip Empty Dates (Weekends) in a Financial Matplotlib Python Graph
Print the Lines of a Log File Which Starts With Date Format "Yyyy-Mm-Dd" in Python
How to Remove Carriage Return in a Dataframe
Animate a Rotating 3D Graph in Matplotlib
Using Buttons in Tkinter to Navigate to Different Pages of the Application
How to Make a Grade Calculator in Python
How to Get Rid of the B-Prefix in a String in Python
How to Extract All Upper from a String - Python
Extract File Name from Read_Csv - Python
How to Tell If Tensorflow Is Using Gpu Acceleration from Inside Python Shell