This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 3 years ago.
I am trying to delete duplicate elements in a array. There are lots of methods out there but I am trying to come up with my own one and tried the folllowing code.
x=[2,1,3,5,3,5]
for i in range(0,len(x)):
for j in range(0,len(x)):
if (x[i]==x[j+1]):
del x[j+1]
for k in range(0,len(x)):
print(x[k])
I get the following error at line 4
list index out of range.
Please help me!
There are two errors I can see:
You are using j+1 in your program. When the second for loop reaches the end of the loop, j would equal 5, and then j+1 would equal 6, but x[6] would be out of bounds.
Deleting the element from the array changes the length of the array. For example, your array starts with a length of 6, but then, after one of the elements is deleted, it instead has a length 5. However, the for loop doesn't recognize this, and still goes until i=5 instead of stopping at i=4, and x[5] is out of bounds.
Related
This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
List of dictionary stores only last appended value in every iteration
(4 answers)
How do I clone a list so that it doesn't change unexpectedly after assignment?
(24 answers)
Closed last month.
I am writing my first python program for a school project. It is a program to simulate an experiment where you randomly move ones and zeroes around in a matrix. I already wrote 90 % of it and it works ok. I am struggling with one last part - I wrote a for loop that swaps the positions of all ones and zeroes in a list, nested it in a loop which repeats that process a number of times, and am trying to nest it in another loop which would append the resulting lists to an empty matrix one after another a given number of times. The problem I am facing is that all these lists are the same and are supposed to be different.
this is the piece of code I am using. n is the number of the matrix' s columns, m is the number of rows and x is the number of times the ones and zeroes get swapped around in a single row. I am using a swap positions function from geeksforgeeks.
for example when we have a 4x4 matrix and want to mix 2 times:
n = 4
m = 4
x = 2
podlista = [0, 0, 1, 1]
def swapPositions(list, pos1, pos2):
first_ele = list.pop(pos1)
second_ele = list.pop(pos2 - 1)
list.insert(pos1, second_ele)
list.insert(pos2, first_ele)
return list
macierz = []
for w in range(m):
for y in range(x):
for k in range(n):
import random
swapPositions(podlista, k, random.randint(0, (n - 1)))
macierz.append(podlista)
print(macierz)
where podlista means row and macierz is matrix
This is the only way I can think of doing this
I would really apreciate some help on this matter
This question already has answers here:
Strange result when removing item from a list while iterating over it
(8 answers)
How to remove items from a list while iterating?
(25 answers)
Closed 12 months ago.
I was trying to sort a list using for loops in python.
I wrote the code like this.
L=[1,2,3,6,7,9,4]
NL=[]
for i in L:
NL.append(min(L))
L.remove(min(L))
print(NL)
But here the output is [1, 2, 3, 4].
I can't understand why the output is stopping at 4. I am new to coding. It would be helpful if someone could help me with this.
You're removing elements from a list while looping over it, which is problematic (if the index of the element you're removing is before your current loop index, the "next element" being shifted back by one won't be visited). As you don't need to work with the index anyways, you can simply loop n times, where n is the number of elements in the list (the length of the list):
L=[1,2,3,6,7,9,4]
NL=[]
for _ in range(len(L)):
NL.append(min(L))
L.remove(min(L))
print(NL)
Side note: The algorithm you've implemented is called "selectionsort" and has quadratic time complexity. You're also emptying the input list. In practice, you should usually be using Python's builtin [...].sort() to sort the input list in place; if you want a sorted copy, you can always call [...].copy() first.
This question already has answers here:
split list into 2 lists corresponding to every other element [duplicate]
(3 answers)
Closed 4 years ago.
Say i have this list:
CP = [1,0,1,0]
How can i print only 0's in the list via indices i.e CP[i].
Required output:
0
0
Any help would be highly appreciated!
This feels like a homework problem, and I assume you actually want odd indices instead of even indices.
Here's a possible solution:
# get a range of all odd numbers between 1 and length of list
# with a step size of 2
for i in range(1, len(CP), 2):
print(CP[i])
The one liner --
print ('\n'.join([str(CP[i]) for i in range(1, len(CP), 2)]))
This question already has answers here:
Removing Item From List - during iteration - what's wrong with this idiom? [duplicate]
(9 answers)
Closed 6 years ago.
I'm new to python and this may be a simple one line or one character answer but I can't seem to wrap my head around it. I have a list I want to iterate through and check if the element in the index after the current index is the same and delete it if it is.
while i < len(list):
if list[i] == list[i+1]:
del list[i];
i+=1;
I know the problem is coming from "if list[i] == list[i+1]:" when I get to end of the list "list[i+1]" will be out of range of the index. The problem is that I don't know how to stop the code when it gets to that point where it goes out of range
Firstly, list is the built-in function of python, so you should never use it for the name of your variables.
And to your problems itself. The fix for your error is simple:
while i < (len(_list) - 1):
if _list[i] == _list[i+1]:
del _list[i]
i+=1;
The reason for the IndexError is that at the last iteration i is already the last index and you are trying to get the element at the i+1 position.
This question already has answers here:
How to remove items from a list while iterating?
(25 answers)
Closed 7 years ago.
I am working of Project Euler problem 2. I need to find the sum of all even Fibonacci numbers up to four million. I have a function that generates all possible Fibonacci numbers up to upperBound which is input by the user. I am passing this list of fibs to another function in order to eliminate the odd values. I am trying to iterate through the list and delete the element if it is odd. It is returning an error saying :
in evenFibs
del list_of_fibs[value]
IndexError: list assignment index out of range
Here is my code for evenFibs() :
def evenFibs(upperBound):
list_of_fibs = getFibs(upperBound)
for value in list_of_fibs:
if value % 2 != 0:
del list_of_fibs[value]
return list_of_fibs
I am not sure why this error is occuring.
Take a note that you shouldn't change array while iterating it, also to delete element from array you should use index of element, not value. You can get index of first element with specific value using index method of list. As for your task, it would be better to use list comprehension:
def evenFibs(upperBound):
list_of_fibs = getFibs(upperBound)
return [value for value in list_of_fibs if value % 2 == 0]