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 Basics (2015) Python Data Types list.remove()

Leur Gallardo
PLUS
Leur Gallardo
Courses Plus Student 188 Points

Multiple removals

How do you remove a string and an integer from a set of lists together

lists.py
states = [
    'ACTIVE',
    ['red', 'green', 'blue'],
    'CANCELLED',
    'FINISHED',
    5,
]
states.remove(5)

Also to delete 'green' from the list

1 Answer

Hi there, my understanding is that there no single command like,

states.remove(5, 'green') 

You can use slice if the elements are next to each other for instance

del states[3::]
['ACTIVE', ['red', 'green', 'blue'], 'CANCELLED']

still not really solving your needs

The only way I can think of doing this is to create your own function

def remove_items(states, remove_list):      # function to remove multiple items 
    for i in states:                        # iterate through the list    
        if isinstance(i, list):             # is the item in the list a list?
            remove_items(i, remove_list)    # if yes call the remove_items function on that list
        if i in remove_list:                # if the item is in the remove_list 
            states.remove(i)                # remove item
    return states                           # return the list


if __name__ == '__main__':

    states = [
        'ACTIVE',
        ['red', 'green', 'blue'],
        'CANCELLED',
        'FINISHED',
        5,
    ]     

    remove_list = ['CANCELLED', 'blue']

    print(remove_items(states, remove_list))

This may come in handy if you do not know beforehand what is in the list !!!

Hopefully of some use.