This question already has answers here:
Replace values in list using Python [duplicate]
(7 answers)
Closed 4 years ago.
I have a given list, with 49 variables each with a value between 1-5. I want to change the value of all variable which is equal to 5 to zero.
Here is what I’ve tried:
For element in listb:
If element == 5:
element = 0
But it doesn’t have any affect, what is the problem?
Thanks
Vendel
Using list comprehension:
listb = [n if n!=5 else 0 for n in listb]
Which is a more efficient alternative to
for index in range(listb):
if listb[index] == 5:
listb[index] = 0
Infact in for element in listb: element is a copied primitive.
This would be different if we had:
listb = [[1],[5],[3]]
for element in listb: #element is a copied reference, but to the same element in listb
if element[0] == 5:
element[0] = 0
Related
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed last year.
I've been given a list of integers called nums, and am trying to remove all occurrences of the value (val). I'm trying to see where val matches an index of nums and am trying to remove it from the list. However, I keep getting a "list index out of range" error. I'm guessing it is because as I am popping the element of nums that matches val, it shrinks the list so it goes out of range. Is it not possible to remove all occurrences of value in this way?
nums = [3,2,2,3]
val = 2
for i in range(len(nums)):
if val == nums[i]:
nums.pop(i)
print(nums)
You should not try to remove elements from the list as you're iterating over it, as the memory is shifting as you're accessing it.
Instead, you should create a new list:
nums = [3,2,2,3]
val = 2
print([num for num in nums if val != num]) # Prints [3, 3]
use remove method to remove vlaues from list
nums = [3,2,2,3]
val = 2
l = list(nums)#creating new list
for v in l:
if v == val:
nums.remove(val)#removing values
print(nums)
output:
$ python3 file.py
[3, 3]
This question already has answers here:
Change values in a list using a for loop (python)
(4 answers)
Closed 3 years ago.
There is probably a matching question out there. I have a globally defined list and I am trying to iterate through the list and edit certain elements by using specific if statements. My problem is that when I print the list before the loop and when I print the list afterwards they are still the same.
I've considered using enumerate to manually edit list["enumerated number"] using the numbers connected to the element but this seems clumsy.
print(list)
for el in list:
print(el)
if el < 1:
el = 0
elif el > 1:
el = 2
print(list)
I am hoping to get an output that is the top list edited according to the if statements.
As Derek Langley suggested, you can do it by indexing the list. Rather than range(len(list)), it's a good habit to use enumerate(list)
print(list)
for index, value in enumerate(list):
print(value)
if value < 1:
list[index] = 0
elif value > 1:
list[index] = 2
print(list)
Edit: I would have added this as a comment, but I don't have enough points yet!
The reason this doesn't work is that Python variables are just names. Each pass through the loop, el is initially set to be a name for whatever is at the next list index. If the next value was 3, for example, the computer will now replace el with 3 whenever it occurs.
But when you have a statement like el = 2, all you are doing is telling the computer that from now on, el is just another name for the number 2. You have not actually edited the underlying list element. In order to do this, you will need to do something like this:
for i in range(len(list)):
print(list[i])
if list[i] < 1:
list[i] = 0
elif list[i] > 1:
list[i] = 2
The reason this would work is that instead of giving a name to each list element, and then giving that name to something else, you are actually changing the list elements themselves.
Try this instead:
for i in range(len(list)):
if list[i] < 1:
list[i] = 0
elif list[i] > 1:
list[i] = 2
I believe the reason why your code isn't working is because you are referencing the object inside the list, and not the object's position.
This question already has answers here:
one-liner to check if at least one item in list exists in another list? [duplicate]
(6 answers)
Closed 6 years ago.
I have created two lists in python list1 and list2.
I want to start at the first element in list 1 and search for that element in list 2 if it exists print something, if it does not exist print something else
I'm not sure how to march through list 1 and search list2 for value. I know this will involve a for loop.
for in list1
if values =
print("True")
else:
print("False)
for item in list1:
if item in list2:
print 'yes'
else:
print 'no'
This question already has answers here:
Accessing the index in 'for' loops
(26 answers)
Closed last month.
I would like to find the corresponding item in a list but the code below seems to find the corresponding item and then moves on item further as shown:
a = [1,2,3,4]
b = [5,6,7,8]
for i in a:
if i == 1:
print b[i]
Which gives me:
6
When I thought it should print:
5
In which case I'm now having to write:
print b[i-1]
python list index starts from 0 .
when you try to iterate a list you will be getting each and every element in the list
for example:
a = [1,2,3,4]
for element in a:
print element
will be printing [1,2,3,4]
incase if you want to get the index along with the element you should use
enumerate function
for example:
a = [1,2,3,4]
for index, element in enumerate(a):
print index, element
will be printing
0,1 where 0 is the index of 1 in list
1,2
2,3
3,4
in you program you can use enumerate to achieve what you want
a = [1,2,3,4]
b = [5,6,7,8]
for index, i in enumerate(a):
if i == 1:
print b[index]
will yield you the result you want.
Your condition is i==1, so when this is satisfied it naturally always looks up the second element (counting from 0) of b. (If the value 1 appeared at some other location in a, the workaround b[i-1] you are using would fail.)
I suspect what you want is
a = [1,2,3,4]
b = [5,6,7,8]
print b[a.index(1)]
(note that this avoids the unnecessary for loop). But your question isn't clear.
In your code, i==1 corresponds to the 0th element of a.
a.index(i) gives us the index with which we can print the corresponding element of b.
a = [1,2,3,4]
b = [5,6,7,8]
for i in a:
if i == 1:
print b[a.index(i)]
This would print the first element of b i.e 5
The reason, as everyone has mentioned, is because Python lists are 0-based.
When i == 1, you then print b[i] == b[1] == 2
To get the index, you need to use enumerate, which returns the index then the element at that index.
Here's how you should use it.
for idx, elem in enumerate(a):
if elem == 1:
print b[idx]
This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
Closed 7 years ago.
I am trying to delete duplicate elements in the list. The code below says index out of range when the value of i goes to 9. 9 + 1 = 10 is not outside the list and I can print it, but whenever I use del it gives me error. This is the code that doesn't work:
a = [12,12,34,34,56,11,32,32,11,10,10]
g = len(a)
for i in range(0,g-1):
if a[i] == a[i+1]:
del a[i]
print a
However the reverse logic which is I having value from 10 - 1 works but i from 0 - 9 doesn't work. This one works the reverse logic.
a = [12,12,34,34,56,11,32,32,11,10,10]
g = len(a)
for i in range(g-1,0,-1):
if a[i] == a[i-1]:
del a[i]
print a
Can someone explain why, please?
You are deleting elements off the list, so it gets shorter.
You should create a new list:
last = None
b = []
for value in a:
if value != last:
b.append(value)
last = value