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
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:
python : list index out of range error while iteratively popping elements
(12 answers)
Closed 1 year ago.
Does anyone know why this code wouldnt work if there was hypothetically an empty list. When I run a test for the empty list it give me indexerror that it is out of range.
def dedup(l):
dl = [l[0]]
for v in l[1:]:
if dl[-1] != v:
dl.append(v)
return dl
If the list is empty, l[0] does not exist (there is no first element).
You can add an explicit check for that.
dl = [l[0]] if l else []
# or
if not l: return l
dl = [l[0]]
This is because in an empty list how can you access the elements using index as there are no elements in it.
When you use l[0] the first element will be accessed. But in an empty list there is no first element. Hence the reason for the error
You need to check whether the import array is empty or not
if len(l) != 0:
I'd test for the case when there is either 0 or 1 and return as well.
ETA: of course list(set()) also works.
def dedup(l):
if len(l) < 2:
return l
dl = [l[0]]
for v in l[1:]:
if dl[-1] != v:
dl.append(v)
return dl
print(dedup([1, 1, 11, 3]))
print(dedup([]))
print(list(set([1, 1, 11, 3])))
print(list(set([])))
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
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:
python lists, appending something to the list changes the entire thing?
(3 answers)
Closed 8 years ago.
x = raw_input("")
y = raw_input("")
a = []
b = []
count = 1
for i in range(0, int(y)):
b.append(count)
count+=1
for i in range(0, int(x)):
a.append(b)
for i in a:
print ""
for j in i:
print j,
a[1][1] = 0
for i in a:
print ""
for j in i:
print j,
a has been created by appending list "b" n time to it
Now when i modify a[1][1] the whole column that is a[0][1] - a[n][1] gets modified to that value
Can anyone explain why this is happening
Every time you append b, you are appending the same list -- not copies of the list, but multiple references to the same object. If you want each row to be a different list, you need to append a new list each time, by doing a.append(b[:]).
That is because by appending b, you are creating pointers to the same objects. Instead, make a copy as follows:
for i in range(0, int(x)):
a.append(b[:])
You can see it working as expected, here