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 Collections (Retired) Lists Redux Combining Lists

List Range

How would you start to toss out the older numbers in the list? If you wanted to have only 10 numbers in a list and you kept writing to the list (11,12, so forth) but only wanted to keep ten in the list. How would you removes (1,2, so forth)

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

Just off the top of my head:

def add_to_list(lst, thing_to_add):
    if len(lst) == 10:
        lst.pop()
    lst.append(thing_to_add)

Then call this once for each thing to add. You could modify if to take an iterable of things to add but then you'll need to do some length calculation before you start popping items and appending items, so it's more work. This modifies lst (or whatever it refers to) in place, so you'll want to be careful with it.