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 trial

Python Python Collections (2016, retired 2019) Lists Removing items from a list

aditya yadav
aditya yadav
1,505 Points

pls help

Pls help with the code,

  1. why this code is wrong
  2. how can we do in one step using insert and pop

thanks in advance

lists.py
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
for i in range(1,4):
        del messy_list[0]

Hey Aditya Yadav,

Looks like that your code indentation is with more than 4 spaces on row 3.

You are also doing a range from (1,4), getting only the values [2, 3, 1] of your array, remember, an array starts with index 0, and when you do a range from x to y, you are getting the content of index x to (y-1), in this case (1 to 3), resulting in the values 2,3,1.

If you only want to remove the first value of your array, you can do this in some ways:

messy_list.pop(0) or del messy_list[0]

Cheers, Felipe

1 Answer

Hey Aditya!

the insert method can insert a specific item at any index at the array. Here is how it works:

array = [2, 3, 5]
array.insert(0,1) # This will insert the int 1 at index 0
array.insert(3, 4) # This will insert the int 4 at index 3
print(array) # This will print out [1, 2, 3, 4, 5]

With that said, you can insert an item you just poped from the array using this statement:

array.insert(0, array.pop(2)) # This will insert the item poped from index 2 back at index 0

So, applying it to your code, you can do it in one statement like this:

messy_list.insert(0, messy_list.pop(3))

After that, you have to remove the string (wich is more like a char), the boolean and the list from the messy_list. You can remove items from a list using .remove(). So, to complete this task, you can remove all that from the list using:

messy_list.remove('a')
messy_list.remove(False)
messy_list.remove([1, 2, 3])