Basic List Operations

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.)


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

Lists, like strings, can be assigned to variables. They can also be accessed one item at a time using the familiar square bracket notation.


>>> 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.


>>> len(names)
4
                    

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


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

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

Note: the order in which the two lists were added, is preserved. Subsets of lists can also be retrieved. This requires the same notation used with strings.


>>> 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.