Lists In Python
Python Lists: Comprehensive Theory
Lists are used to store multiple items in a single variable. They are one of the 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
1. Characteristics of Lists
- Ordered: The items have a defined order, and that order will not change. If you add new items to a list, the new items will be placed at the end of the list.
- Changeable (Mutable): We can change, add, and remove items in a list after it has been created.
- Allow Duplicates: Since lists are indexed, they can have items with the same value.
2. List Items & Indexing
List items are indexed, the first item has index [0], the second item has index [1], etc.
thislist = ["apple", "banana", "cherry"]
print(thislist[0]) # Output: apple
Negative Indexing
Negative indexing means starting from the end of the list. -1 refers to the last item, -2 refers to the second last item, etc.
print(thislist[-1]) # Output: cherry
Range of Indexes (Slicing)
You can specify a range of indexes by specifying where to start and where to end the range.
fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(fruits[2:5]) # Output: ['cherry', 'orange', 'kiwi']
3. Modifying List Items
To change the value of a specific item, refer to the index number:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist) # ['apple', 'blackcurrant', 'cherry']
4. List Methods
Python has a set of built-in methods that you can use on lists:
| Method | Description | Example |
| :--- | :--- | :--- |
| append() | Adds an element at the end of the list | list.append("orange") |
| insert() | Adds an element at the specified position | list.insert(1, "orange") |
| remove() | Removes the item with the specified value | list.remove("banana") |
| pop() | Removes the element at the specified position | list.pop(1) |
| clear() | Removes all the elements from the list | list.clear() |
| sort() | Sorts the list | list.sort() |
| reverse() | Reverses the order of the list | list.reverse() |
5. List Comprehension
List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list.
Syntax:
newlist = [expression for item in iterable if condition == True]
Example:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist) # ['apple', 'banana', 'mango']
6. Nested Lists (Matrix)
A list can contain another list as an item. This is called a nested list.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[0][1]) # Output: 2