+ 5
Can you help me with this code?
https://code.sololearn.com/ck7U6GdseKC1/?ref=app This code should remove even numbers feom the list but it doesn't work properly and doesn't remove all the even numbers. Can you explain it to me? Why doesn't it work?
14 odpowiedzi
+ 11
If you reverse the direction of the loop so that it removes from the end of the list, the lower indices will not get shifted by the remove. Here is a quick fix:
for i in lst[::-1]:
+ 9
Sana Sharifi ,
just to complete the possible solutions, we can also use this for iterating over the numbers list:
...
for i in lst[::]:
...
the mentioned solution from Brian and the above shown, are the only one that are working inplace, means without creating a new additional output list.
not to forget this version that uses the built-in function reversed(), that creates a reversed iterator:
...
for i in reversed(lst):
...
+ 8
Abdurahman Jemal ,
nice approach, i was not aware of this. only the efficiency of the code is a little less favorable, because we need more execution steps compared to a version like Brian's. his code takes 30 steps, the code mentioned by you takes 40 steps.
+ 6
Using the remove method also changes the index of the other characters in the list.
Perhaps, instead of using remove you could append the even numbers to a new list!
+ 3
You can use the filter function too...
+ 3
A container object like list produces a fresh new iterator each time used in a for loop. So we have to use the following type of tricks:
https://code.sololearn.com/cjYi2F99p5Am/?ref=app
for i in lst:
for j in lst:
if j % 2 == 0:
lst.remove(j)
print(lst)
+ 2
Keith Driscoll thnx a lot for your help❤️✨
+ 2
Ali Mechanic I just searched it on google and read about it. thank you :)🤝❤️
+ 2
Note that we use the for loop when we already know the number of iterations, and a while loops when there is a condition that need to be met.
Using a while loop I found the following two solutions.
The first one uses slicing to remove even numbers:
https://code.sololearn.com/col3LV61b35Z/?ref=app
It is as follows:
lst = list(range(100)) # Creates a list of 100 numbers.
i = 0 # Initialize i
while i < len(lst):
if lst[i] % 2 ==0:
print(lst[i]) # You can comment this line
lst[i:i+1] = []
print(lst[i]) # You can comment this line
i += 1 # This means i = i + 1
print(lst) # Displays lst
The second uses remove() function to remove even numbers:
https://code.sololearn.com/cH0U6IDp7mEG/?ref=app
It is as follows:
lst = list(range(100)) # Creates a list of 100 numbers.
i = 0 # Initialize i
while i < len(lst):
if lst[i] % 2 ==0:
print(lst[i]) # You can comment this line
lst.remove(lst[i])
print(lst[i])
i += 1
print(lst)
+ 1
Sana Sharifi قربانت...🌱🌹
+ 1
https://code.sololearn.com/cAlpl245B132/?ref=app
Hope this helps (used filter instead of for loop)
0
You can make a new list and add the elements to it:-
lst = [14,25,12,18,2,24,7,15,30,60]
new = []
for i in lst:
if i % 2 != 0:
new.append(i)
print(new)
0
Hi