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 (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.