Posts: 1
Threads: 1
Joined: Jan 2024
Jan-27-2024, 09:06 AM
(This post was last modified: Jan-27-2024, 09:34 AM by Yoriz.
Edit Reason: Added code tags
)
list=[6.2,5.9,4.8,6.1,6.1,6.5,5.9,5.8,6.2]
for a in list:
if a<=6.0:
list.remove(a)
print(list)The output i am getting is : Output: [6.2, 4.8, 6.1, 6.1, 6.5, 5.8, 6.2]
Q> Why 5.8 is NOT getting removed ?
Posts: 2,167
Threads: 35
Joined: Sep 2016
Jan-27-2024, 09:43 AM
(This post was last modified: Jan-27-2024, 09:50 AM by Yoriz.)
Removing an item from the list while looping over it changes the index location of the remaining items.
You can loop over a copy of the list and remove items from the original list
values=[6.2,5.9,4.8,6.1,6.1,6.5,5.9,5.8,6.2]
for value in values[:]:
if value<=6.0:
values.remove(value)
print(values)Output: [6.2, 6.1, 6.1, 6.5, 6.2]
Also note that you shouldn't use list as the variable name to contain your list as it overwrites the keyword list
sg_python likes this post
Posts: 1,300
Threads: 151
Joined: Jul 2017
Jan-27-2024, 10:15 AM
(This post was last modified: Jan-27-2024, 10:16 AM by Pedroski55.)
As Yoriz said, it is not good to remove items from a list while you are looping through it. Will cause problems!
Nor is it good to use the reserved word list as you did.
You could approach this from the other way round, instead of slicing out a copy, create a new list to start with and append:
mylist=[6.2,5.9,4.8,6.1,6.1,6.5,5.9,5.8,6.2]
mynewlist = []
for a in mylist:
if a>=6.0:
mynewlist.append(a)
print(mynewlist)Output: [6.2, 6.1, 6.1, 6.5, 6.2]
I think it is a good idea to preserve the original list for later use perhaps.
sg_python likes this post
Posts: 6,981
Threads: 22
Joined: Feb 2020
A list comprehension would work well here
values = [6.2, 5.9, 4.8, 6.1, 6.1, 6.5, 5.9, 5.8, 6.2]
print([value for value in values if value > 6])
Pedroski55 and sg_python like this post
Posts: 4
Threads: 0
Joined: Apr 2026
Nice thread questions like this are exactly why communities like Python Forum are so helpful for debugging and improving coding skills. When you're stuck on an issue, the best approach is usually to simplify the code, isolate the problem, and test each part step by step instead of trying to fix everything at once.
Also, adding small debug prints or checking variable values during execution can quickly reveal where things are going wrong. That method saves a lot of time and helps you understand the logic better in the long run.
If you can share the exact error or expected vs actual output, it would be much easier for others to give a precise solution 👍
|