Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialAbdillah Hasny
Courses Plus Student 3,886 PointsWhy i can't remove all char with this loop
import string
my_list = [1,2,3,'a','b','d',5,'f','h']
alphabet = list(string.ascii_lowercase)
for item in my_list:
if item in alphabet:
while True:
try:
my_list.remove(item)
except:
break
print(my_list)
what is wrong in my code , i still get char inside my_list after removing them in the loop who have any char inside
[1, 2, 3, 'b', 5, 'h'] b and h still in the list
1 Answer
Gunhoo Yoon
5,027 PointsI think that's happening because list is keep mutating on the fly.
Let's say your algorithm reached 'a' at index 3.
'a' is removed since it's lowercase char and 'b' takes index 3 since list is mutable.
The loop points to next index which is 4.
'b' is not at index 4 anymore it is 'd'
Same thing happen for 'f' and 'h'
Try this I haven't tested it yet but it will work.
import string
my_list = [1,2,3,'a','b','d',5,'f','h']
#made copy of list. Actual copy that doesn't share any reference.
#I originally did copied_list = my_list then found out they are treated like object.
copied_list = my_list[:]
alphabet = list(string.ascii_lowercase)
for item in copied_list:
if item in alphabet:
while True:
try:
my_list.remove(item)
except:
break
print(my_list)
#What i mean by my mistake up there.
a = [1, 2, 3]
b = a
c = a[:]
a.append(4)
print(a, b) #[1,2,3,4] [1,2,3,4]
print(c) #[1,2,3]
Abdillah Hasny
Courses Plus Student 3,886 PointsAbdillah Hasny
Courses Plus Student 3,886 Pointsi get the idea .. thanks Gunhoo Yoon