Append

The append(item) function adds an item to the end of a list. This function mutates a list rather than creating a copy of the list.

This is different from the append block in Snap!, which will combine multiple lists into a single list.


>>> idiom = ["peas", "in", "a"]
>>> idiom.append("pod")
                    

>>> idiom
["peas", "in", "a", "pod"]
                    

Object Oriented Programming
You might be wondering why we put .append("pod") after the idiom list. This is an instance of Object Oriented Programming (OOP), which we talked about in the Programming Paradigms lecture. The list idiom is an object. Objects can have their own functions. In Python, every list object has an append function. In contrast with the add block in Snap!, when we use the .append("pod") function we don't need to specify which list to use. The reason for that is that we are telling the idiom object to use its append function.

Insert

If you want the list to add the item to a specific location instead of the end, you'd use the insert(index, item) function to specify the desired index. The first argument is the desired index, the second argument is the item you want to insert.


>>> remark = ["break", "leg"]
>>> remark.insert(1, "a")
                    

>>> remark
["break", "a", "leg"]
                    

Pop

Finally, use pop(index) to remove the item at position index in the list. If no argument is given (e.g. crime.pop()) the last item of the list will be removed.


>>> crime = ["dont", "steal", "the", "cookie"]
>>> crime.pop()
'cookie'
                    

>>> crime
["dont", "steal", "the"]
                    

In Snap! the delete block does not report the deleted item. In contrast, Python's .pop(index) function does return the item that it removes.