Basic List Operations

Open the Python interpreter and type out the examples for yourself! This way, if you are wondering what would happen if you tried something, you can just do it. Also, typing is better practice than simply reading.

A basic list can be constructed with comma separated elements between square brackets, [] . These lists can be of any length and can contain any type or mix of data (strings, numbers, etc.), just like in Snap!.


>>> names = ["John", "Paul", "George", "Pete"]
                    

Lists, like strings, can be assigned to variables. To access a particular item of a list, we use the familiar square bracket notation that we saw with strings in the previous lab.


>>> names[0]
'John'
                    

The length of a list is important and can be retrieved using the built-in len() function. This same function can also be used for strings.

Notice that, like with strings, the first item of a Python list is item 0 (not item 1 as in Snap!).


>>> len(names)
4
                    

To join two lists together, use the "+" operator. This returns a new list containing all items of both lists.


>>> names = ["John", "Paul"] + ["George", "Pete"]
                    

(If you haven't used it, the append block comes from the Tools library.)


>>> names
["John", "Paul", "George", "Pete"]
					

>>> names[1:3]
["Paul", "George"]
>>> names[2:]
["George", "Pete"]
        

As with strings, the colon : without a number on either side returns a sublist extending completely to either the beginning or end of the list.