Table of Contents
A list in Python is an ordered, mutable collection that can hold multiple items even of different data types. Think of it like a container where you can store your favourite things, rearrange them or remove them whenever you like.
Lists are one of the most powerful, flexible and frequently used data structures in Python. They help you store, organise and manipulate multiple pieces of data whether it’s numbers, strings or even other lists!
Consider a simple example below.
animals = ["cat", "dog", "donkey"]
print(animals)
# output
# ['cat', 'dog', 'donkey']
Creating Lists in Different Ways
There are two methods:
- By using a square bracket [ ].
- By using the list() constructor.
Lists are defined by enclosing elements within square brackets ([]), with each item separated by a comma. When using a string inside a list, it should always be enclosed in single or double quotes. Individual characters of a string should also be quoted.
Write a Python program to declare a list of numbers using both methods.
numbers = [1, 2, 3, 4, 5]
letters = list(('a', 'b', 'c'))
print(numbers)
print(letters)
# output
# [1, 2, 3, 4, 5]
# ['a', 'b', 'c']
Accessing Elements in a List
Each element in a list is accessible via its index which always starts counting from 0.
Elements can also be retrieved by using negative indexing. Negative indexing begins with -1 for the last element and continues backward -2, -3 etc.
Elements can also be retrieved by using a custom range. For example
names[2:4]: Retrieves elements starting from index 2 and stops before index 4
names[:3]: Starts at the beginning of the list and stops before index 3.
names[2:]: Starts at index 2 and continues till the end of the list.
Write a Python program to declare a list and access individual items by indexing and negative indexing and also use custom indexing.
names = ["Jon", "Stiffany", "Malina","Jake","Alex","Jimmy","Klassen"]
print(names[0]) # Jon
print(names[2]) # Malina
print(names[-1]) # Klassen
print(names[2:5]) # ['Malina', 'Jake', 'Alex']
print(names[:4]) # ['Jon', 'Stiffany', 'Malina', 'Jake']
print(names[2:]) # ['Malina', 'Jake', 'Alex', 'Jimmy', 'Klassen']
List Modification
1. Modification:
Replaces an element in the specified index.
- Syntax: list_name[index] = element
2. Addition:
The append() function can be used to add an element at the end of the list.
- Syntax: list_name.append(element)
3. extend:
Multiple elements can be added at the end of the list.
- Syntax: list_name.extend(elements_list)
4. Insertion:
Insert an element at a specific location.
- Syntax: list_name.insert(index_value, element)
fruits = [‘apple’, ‘banana’, ‘cherry’, ‘grape’, ‘lime’]
Consider the above list and write a Python program to modify the elements, perform modifications, and append and insert an element at a specified location.
fruits = ['apple', 'banana', 'cherry', 'grape', 'lime']
print(f"Initial List: {fruits}")
# 1. MODIFICATION
fruits[1] = "mango" # replaces element in index 1 with mango.
print(f"1. {fruits}")
# 2. Addition
fruits.append("orange") # appends orange at the last of the list.
print(f"2. {fruits}")
# 3. extend
fruits.extend(["blackberry", "pomegranate", "custard apple"])
print(f"3. {fruits}")
# 3. Insertion
fruits.insert(1, "kiwi") # inserts kiwi at index 1 and pushes the current elements to the next index.
print(f"4. {fruits}")
# output
# Initial List: ['apple', 'banana', 'cherry', 'grape', 'lime']
# 1. ['apple', 'mango', 'cherry', 'grape', 'lime']
# 2. ['apple', 'mango', 'cherry', 'grape', 'lime', 'orange']
# 3. ['apple', 'mango', 'cherry', 'grape', 'lime', 'orange', 'blackberry', 'pomegranate', 'custard apple']
# 4. Insert Result: ['apple', 'kiwi', 'mango', 'cherry', 'grape', 'lime', 'orange', 'blackberry', 'pomegranate', 'custard apple']
5. Deletion:
There are four different methods of deletion in Lists.
a) Remove by Value (remove()): Remove the element by its name.
- Syntax: list_name.remove(element)
b) Remove by index (Pop()): Remove the element by its index.
- Syntax: List_name.pop(element_index)
c) Remove by Keyword (del): The del statement is used to remove the element.
- Syntax: del List_name[index_of_element_to_be_removed
d) Remove all elements in a List: Used to empty the List.
- Syntax: List_name.clear()
fruits = [‘apple’, ‘kiwi’, ‘mango’, ‘cherry’, ‘grape’, ‘orange’]
Consider the above list and perform all delete operations
fruits = ['apple', 'kiwi', 'mango', 'cherry', 'grape', 'orange']
# 1. Remove by Value ()
fruits.remove("apple")
print(f"1. {fruits}")
# 5. Remove by Index ()
popped_item = fruits.pop(2)
print(f"2. ('{popped_item}'): {fruits}")
# 6. Remove by Keyword
del fruits[0]
print(f"3. {fruits}")
# 7. Remove All Items (clear())
fruits.clear()
print(f"4. {fruits}") # 4. []
# output
# 1. ['kiwi', 'mango', 'cherry', 'grape', 'orange']
# 2. ('cherry'): ['kiwi', 'mango', 'grape', 'orange']
# 3. ['mango', 'grape', 'orange']
Additional List Functions
1. sort():
used to sort the list alphabetically or numerically.
- Syntax: list_name.sort()
2. reverse():
reverses the list.
- Syntax: list_name.reverse()
3. count():
counts the number of times a particular value appears in a list.
- Syntax: list_name.count(element)
4. copy():
runs a shallow copy of the list, meaning the new list is independent of the original.
- Syntax: new_list=list_name.copy()
fruits = ['grape', 'apple', 'banana', 'apple', 'cherry']
print(f"Initial List: {fruits}")
fruits.sort()
print(f"1. {fruits}")
# 1. ['apple', 'apple', 'banana', 'cherry', 'grape']
fruits.reverse()
print(f"2. {fruits}")
# 2. ['grape', 'cherry', 'banana', 'apple', 'apple']
count_apples = fruits.count("apple")
print(f"3. Count of 'apple': {count_apples}")
# 3. Count of 'apple': 2
new_list = fruits.copy()
fruits.append("orange")
print(f"4. The Copy (new_list): {new_list}")
print(f" Original list after append: {fruits}")
# 4. The Copy (new_list): ['grape', 'cherry', 'banana', 'apple', 'apple']
# Original list after append: ['grape', 'cherry', 'banana', 'apple', 'apple', 'orange']
Advanced Tricks with Lists
5. Comprehension:
List comprehension is a concise and highly efficient way to create a new list in Python by defining a complete loop and logic sequence within a single pair of square brackets [ ].
Write a Python program to print the square of numbers from one to ten.
squares = [x**2 for x in range(11)]
print(squares)
# output
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
| Step | Value of x | Expression | Output |
|---|---|---|---|
| 1 | 0 | 0 ** 0 | 0 |
| 2 | 1 | 1 ** 1 | 1 |
| 3 | 2 | 2 ** 2 | 4 |
| 4 | 3 | 3 ** 3 | 9 |
| 5 | 4 | 4 ** 4 | 16 |
| 6 | 5 | 5 ** 5 | 25 |
| 7 | 6 | 6 ** 6 | 36 |
| 8 | 7 | 7 ** 7 | 49 |
| 9 | 8 | 8 ** 8 | 64 |
| 10 | 9 | 9 ** 9 | 81 |
| 11 | 10 | 10 ** 10 | 100 |
| 12 | 11 | Stop Loop | - |
6. Nested List:
Nested lists (or lists of lists) are lists in Python that contain other lists as their elements.
matrix = [[1, 2], [3, 4], [5, 6]]
print(matrix[1][0])
# output
# 3
7. Joining (List Concatenation):
Any two or more lists can be concatenated. There are:
Using the ‘+’ operator (Syntax: list1_name + list2_name)
Using the append: The append() method adds the entire second list as a single, nested element to the end of the first list. (Syntax: List1_name.append(List2_name)
Using extend (Syntax: List1_name.extend(List2_name))
Consider an example below to demonstrate all three methods
list1 = [1, 2, 3]
list2 = [4, 5]
combined = list1 + list2
print(combined)
# [1, 2, 3, 4, 5]
list1 = [1, 2, 3]
list2 = [4, 5]
list1.append(list2) # Adds list2 AS A SINGLE ELEMENT: [1, 2, 3, [4, 5]]
print(list1)
# [1, 2, 3, [4, 5]]
list1 = [1, 2, 3]
list2 = [4, 5]
list1.extend(list2) ## Adds individual elements: [1, 2, 3, 4, 5]
print(list1)
# [1, 2, 3, 4, 5]
FAQ (Frequently Asked Questions)
1. How to sort a list in Python?
We can simply use the sort() method or the sorted function to sort the elements.
numbers = [5, 2, 9, 1]
numbers.sort()
print(numbers)
or
sorted_list = sorted(numbers)
2. How to reverse a list in Python?
There are two ways:
1) By using reverse()
fruits = [“apple”, “banana”, “cherry”]
fruits.reverse()
print(fruits)
2) By using Slicing
reversed_list = fruits[::-1]
3. How to append a list in Python?
We can use the append() method to add an element at the end of the list.
fruits = [“apple”, “banana”]
fruits.append(“cherry”)
print(fruits)
[‘apple’, ‘banana’, ‘cherry’]
4. How to iterate through a list?
We can iterate through the list by using either a for loop or a while loop. Check the example in the above content.
5. How to convert a string to a list in Python?
A string can be converted to a list by using two ways
1) By using Split()
text = “I love Python”
words = text.split()
print(words)
# [‘I’, ‘love’, ‘Python’]
2) Using list()
text = “hello”
letters = list(text)
print(letters)
# [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]
split breaks the text by white spaces and the list() splits every character.
6. Is a list mutable or not?
Yes lists in Python are mutable. Elements can be inserted, removed or modified once the list is created.
7. What is the difference between a list and a tuple?
| List | Tuple |
|---|---|
| Mutable | Immutable |
| The contents can be changed after creation | The contents cannot be changed after creation |
| Defined by square brackets ([ ]) | Defined by parenthesis ( ) |
| They are usually slower for retrival because python reserves extra space for future modification | They are faster as their size is fixed |
| Used where data needs to be sorted or changed | They are used in data-base records where data is never changed |