Iterating and changing elements in a list in Python [duplicate] - python

This question already has answers here:
Can't modify list elements in a loop [duplicate]
(5 answers)
Closed 4 years ago.
I'm supposed to find the largest number in a list, and then change all the elements of the list to that number. But when I print the output after the iteration, it still hasn't changed. What am I doing wrong please ?
Ar =[5,4,11]
ArMax = max(Ar)
for i in Ar:
i = ArMax
print(Ar)

The list doesn't change because you've done nothing to change the list. Your list is Ar -- where have you assigned a new value to anything in that list? Nowhere. All you did was to create a local variable to take on the values in Ar, and then change the value of that variable. You never touched the original list. Instead, you have to change the list elements themselves, not their copies. Keeping close to your present code:
for i in range(len(Ar)):
Ar[i] = ArMax
Another way would be to create a new list with those items in it, and simply replace the original list all at once:
Ar = [ArMax] * len(Ar)
This looks to see how long the current list is with len(Ar). Then it takes a one-element list with the max value and replicates it that many times. That new list becomes the new value of Ar.

i = ArMax does not actually assign values to the list because the values of i are copies of the elements in the list. If you want to fix this, try:
for i in xrange(len(Ar)):
Ar[i] = ArMax

Related

How to change the specific values within a dictionary of lists in python [duplicate]

This question already has answers here:
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed 1 year ago.
This is the worst blocker that I have ever had attempting to learn Python. I spent about 10 hours on this one and could really use help.
I want to have dictionaries hold lists in python and then access and change a specific value in those lists. When I do this the way that seems logical to me and access a key then list value, it actually replaces other key's list values.
If I just assign 100 to the key XList it prints 100 for both XList and YList. Why does assigning to one key effect the other???
And if I uncomment the assignment to YList it prints 254 for both. Why can't I assign itemized values to keys and lists like this? How can I assign specific values to lists within dictionaries and access the main lists via keys?? Why does what seems like changing just one keys list value change both key's lists???
testDictKeys= ['XList', 'YList', 'ZList']
testDict = dict.fromkeys(['XList', 'YList', 'ZList'])
noneFillerList = [None] * 30
#Now fill all the columns and row of the dictionary with zeros
for x in range(0,2):
testDict[testDictKeys[x]] = noneFillerList
for x in range(0, 29):
testDict['XList'][x]=100
#testDict['YList'][x]=254
print (testDict['XList'][0])
print (testDict['YList'][0])
Any help is appreciated.
The problem is that you only create one list and assign every dictionary to contain it. To fix the problem, be sure to create a new list to add to each dictionary.

Can you set list indexes as variables in the original list? [duplicate]

This question already has answers here:
How to switch position of two items in a Python list?
(8 answers)
Closed 5 years ago.
I'm trying to print a list of integers, one item per line, after swapping the position of the largest item with the last item.
After swapping the items, they still print in their original position.
large = values[values.index(max(values))]
last = values[-1]
large, last = last, large
for i in values:
print i
I'm sorry if this has already been answered, I haven't been able to find it yet.
You can reach it by:
max_index = values.index(max(values))
values[max_index], values[-1]= values[-1], values[max_index]
When you typed large, last = last, large you need to understand that large and last are variables that separated from the list values. means that even if you change them, the list won't change.
In order to update the list, you need to update the values inside the list as typed above.
You need to reassign large and last to where you would like them to be located in the list. After you make the swap add this:
values[values.index(max(values))] = large
values[-1] = last

Changing list while iterating [duplicate]

This question already has answers here:
Modifying a list while iterating over it - why not? [duplicate]
(4 answers)
Closed 6 years ago.
I've found a python puzzle and can't find out why it works.
x = ['a','b','c']
for m in x:
x.remove(m)
and after this loop x = ['b'].
But why?
As far as I understand for keyword implicitly creates iterator for this list. Does .remove() calls __next__() method so b is skipped? I can't find any mentions of it but this is my best guess.
Here you are iterating over the original list. On the first iteration, you removed the 0th index element i.e. a. Now, your list is as: ['b','c']. On the second iteration your for loop will access the value at index 1 but your index 1 has value c. So the c is removed. Hence resultant list will be ['b'].
In order to make it behave expectedly, iterate over the copy of the list, and remove the item from original list. For example:
x = ['a','b','c']
for m in list(x): # <-- Here 'list(x)' will create the copy of list 'x'
# for will iterate over the copy
x.remove(m)
# updated value of 'x' will be: []
Note: If it is not for demo purpose and you are using this code for emptying the list, efficient way of emptying the list will be:
del x[:]

Strange behaviour when appending items to lists inside dictionaries in python [duplicate]

This question already has answers here:
Dictionary creation with fromkeys and mutable objects. A surprise [duplicate]
(3 answers)
Closed 8 years ago.
I have a dictionary indexed by 201 integer keys (0..200). the value for each of these keys is a list. generated with the code below:
dictionary=dict.fromkeys(range201,[])
i am getting this strange behaviour when i try to append items to the list belonging to one specific index, if i do this:
dictionary[1].append("foo")
i would expect this:
>>dictionary
{0:[], 1:["foo"],2:[],...}
but instead i end up with this:
>>dictionary
{0:["foo"], 1:["foo"],2:["foo"],...}
to clarify a bit the context in which the operation is performed, i am enumerating a list of values that can be None or float, i want to skip the None and append the float to the list corresponding to the enumerate index:
for i, value in enumerate(valuesList):
if value is None:
continue
dictionary[i].append(value)
this is behaviour is independent of which integer index i use, and i end up with the same values at all indices. I could use a list of lists and achieve the same result i think. but i wanted to understand this behaviour.
This is the normal behavior. All the entry of your dictionary where initialized with a reference to the same list. So when appending an element using one key, as all the key are pointing the same list, the modification is applied to all the entries of the dic.
Try this instead :
dictionary={}
for i in range(201):
#the loop make the list.__init__() (i.e. the []) being called 200 times
dictionary[i] = []
dictionary[1].append("foo")
print dictionary

python a=[[],]*10 [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python list confusion
When I write a simple python script, I define a new list as follows:
A=[[],]*10
What I wanna do is just initialize a list whose length is 10 and each element is a empty list.
And when I do something like:
A[0].append(["abc",])
I just wanna append this ["abc",] to A[0], and it turn out to be that every elements in A is appended with ["abc",]
I know this probably due to my initialization (A=[[],]*10) . I just want to know why this happened.
Your expression A=[[]]*10 is equivalent to:
a = []
A = [a]*10
This means that A consists of 10 references to one and the same list.
You are creating a list with 10 references to the same empty list.
You should use a list comprehension instead:
A = [[] for _ in range(10)]
In a list comprehension, you create a new list for every iteration through the loop. If you are using python 2, you should use xrange instead of range (although with only 10 elements that won't make much difference).
All the empty lists are references to the same object.

Categories