Like strings, lists also support concatenation and can be combined to form a single larger list.
Like strings, lists are also indexed, which allows you to grab single values or splice them to get ranges of values. Just like everything else in Python, lists start with 0.
When trying to index a nested list, we simply need to add a second index after the first.
Appending to Lists
You can add values directly to the end of a list with the append() function. You can add anything that is normally allowed in a list.
Below is a list of common list functions. Some of them are similar to other sequences like strings, while others are unique to lists because lists are mutable.
|len(list)||Returns the length of the list .||5|
|x in list|
Will return True if x is within the list, False if not.
Can also be used to iterate through the list.
There is a 4 in the list
|list.index(x)||Will return the index number of item x. Throws an error if item is not found.||2|
|min(list)||Returns the smallest item of list.||1|
|max(list)||Returns the largest item of list.||5|
|list.count(x)||Will return the number of times x appears in the list.||2|
|list.append(x)||Will add x to the end of the list.||[1, 2, 3, 4, 5, 6]|
|list.insert(i, x)||Will insert x at position i.||[1, 5, 2, 3, 4, 5]|
|Will remove the first x from the list.||[1, 3, 2, 4, 5]|
|list.pop([i])||Will remove the item at index i, and return it. If no index is specified, it will remove and return the last item in the list.|
[1, 2, 4, 5]
[1, 2, 4]
|list.reverse()||Will reverse the items in the list.||[5, 4, 3, 2, 1]|
Tuples look similar to lists in that they are defined as a group of comma separated values, but they are enclosed by parenthesis and they are immutable like strings, meaning they can't be altered. Besides that, they are sequences, like lists and strings. This means that tuples have the functionality that other sequences have, such as concatenation, indexing and slicing, and even nesting.
Lists and tuples can also be nested within each other!
All of the functions that work on tuples work on lists, so these should look familiar. However, because they are immutable, not all of the list functions work on tuples. Check out the common tuple functions below.
|len(tuple)||Returns the length of the tuple .||5|
|x in tuple|
Will return True if x is within the tuple, False if not.
Can also be used to iterate through the tuple.
There is a 4 in the tuple
|Returns the smallest item of tuple .||1|
|max(tuple)||Returns the largest item of tuple .||5|