Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics (2015) Python Data Types Lists

removing something from the list

how do l remove something from the list

2 Answers

Cindy Lea
PLUS
Cindy Lea
Courses Plus Student 6,484 Points

Use the remove function. For example:

aList.remove('xyz');

Julian Garcia
Julian Garcia
18,380 Points

Considering a list like a = [1, 2, 3, 4, 2, 'dog', 'cat']

a.remove(2)       remove first 2,  a = [1, 3, 4, 2,  'dog', 'cat']
a.remove('cat'))  remove cat, a= [1, 3, 4, 2,  'dog' ]
a.remove(2)        a= [1, 3, 4,  'dog' ]

you just need to specify the element you want to remove from list but if there are two repeated elements and you want to remove the second one then is better to use del to remove by index, because remove issuing to delete the first occurrence of element from left to right.

if you want to remove by index you can use:

del a[1]     removes first 2,  a= [1, 3, 4, 2,  'dog', 'cat']
del a[-1]    removes the last element,  a= [1, 3, 4, 2,  'dog']
del a[1:3]  delete element 1 and 2 so the result is a= [1, 2,  'dog']