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 trialDean Osborne
3,775 PointsIs it possible to use the insert function to add multiple items to a list rather than one at a time?
None
3 Answers
Kenneth Love
Treehouse Guest TeacherWell, you can .insert()
a member that has multiple values, like inserting a list.
>>> my_list = [1, 2, 3]
>>> my_list.insert(0, [4, 5, 6])
>>> my_list
[[4, 5, 6], 1, 2, 3]
I doubt that's what you're wanting, though. Likely, you're looking for .extend()
.
>>> my_list = [1, 2, 3]
>>> my_list.extend([4, 5, 6])
>>> my_list
[1, 2, 3, 4, 5, 6]
Kenneth Love
Treehouse Guest TeacherAlex Meier No, not with one .insert()
operation. The only way I can think to do this is with slices and some fairly ugly code.
>>> a = [1, 2, 3, 6, 7, 8]
>>> a = a[:3] + [4, 5] + a[3:]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]
sergiu ster
Courses Plus Student 605 PointsIf there is sorting involved, we could use append for the rest of the letters and then list.sort() .
Alex Meier
885 PointsAlex Meier
885 PointsI think the question is whether you can add multiple items to the same list and and specify the index. To use the example in this video, can you add both 'b' and 'e' using one insert line? I couldn't figure out a way to do it and didn't find an answer after googling around.