Late arrivals - why append a list?


#1

Hi everyone,

Why would you append to a list rather than simply insert an item into the original list? It seems cumbersome, but I guess you could insert a raw_input string and have the input apended to a list - is that why? I'm not stuck, just curious.

Thanks.

https://www.codecademy.com/en/courses/python-beginner-en-pwmb1/1/1?curriculum_id=4f89dab3d788890003000096

`


#2

There are two ways to insert an item into a list.

List.append()    # add to end of list

and

List.insert()     # add to beginning of list

To insert in between, we need to create a before and after slice, and concatenate to left and right side of new element.

>>> a_list = [1,2,3,4,6,7,8,9]
>>> a_list
[1, 2, 3, 4, 6, 7, 8, 9]
>>> a_list = a_list[:4] + [5] + a_list[4:]
>>> a_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

Note that the new element is itself a list.


#3

Thanks mtf, but my question is more basic. Why append or insert at all when you can just type the item into the line of code directly where the list is?


#4

Well if you have the raw code, I guess you could manually write the list. The above is in terms of dynamic execution in real time with the program running.

Consider also that this is a lesson. You only have today and possibly tomorrow to finish this track if you wish for it to show up in your progress. The course is being replaced this week. There is not a lot of time left to question the motive of the author. Just try and pick up on the concepts and motor along as best you can to completion.


#5

Thanks for explaining.

In terms of the content replacement, do you know what's staying/going - I'm only 38% through the python course?


#6

As I understand it, the entire old python track is being skuttled. It is possible to complete in a few hours. You get a badge in your CC profile for each completed unit, so just do the best you can. I do not think the earned badges will be affected by the change.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.