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 Growing Lists

How do you user the .insert() and del method in a 2d list

Thank you

1 Answer

Steven Tagawa
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Steven Tagawa
Python Development Techdegree Graduate 14,438 Points

I was curious about this, so I played around a bit in the REPL, and this is what I found.

To use .insert, you have to identify the first index in the variable name. So let's say you have a 2D list called my_list, like so:

my_list = [[1, "first", "1st"], [2, "second", "2nd"], [3, "third", "3rd"]]

...and you want to insert the word "bananas" between "second" and "2nd". In this case your first index is [1] (second list) and your second index is [2] (between the second and third items). To insert at position [1][2], you would say:

my_list[1].insert(2, "bananas")

...which would stick "bananas" before the third item in the second list.

Del is a lot simpler: you just pass both indices. The word "bananas" in my_list is at position [1][2], so to get rid of it you just say:

del(my_list[1][2])

...and it's gone.

Hope this helps!