Python Lists

A Python list is a built-in data structure that allows you to store multiple items (elements) in a single variable. Lists are ordered, mutable, and can contain elements of different types, such as integers, floats, strings, and even other lists.

In Python, a list is used to store collections of items, such as names of people, products in a shopping cart, or tasks in a to-do list.

Creating a List

To create a list in Python, you put the items inside square brackets [] and separate them with commas.

For example:

# List of integers
numbers = [1, 2, 3, 4]

# List of strings
names = ["alice", "james", "robert", "tom"]

# List of mixed data types
mixed_list = ["apple", 12, 3.14]

# Empty list
empty_list = []

Accessing List Items

In Python, you can access items in a list using indexing or slicing.

Accessing a Single Item With Indexing

Indexing allows you to retrieve a single item from a list. Python uses zero-based indexing, meaning the first item is at index 0, the second is at index 1, and so on.

For example:

fruits = ["apple", "banana", "mango", "orange"]
print(fruits[0]) # Output: apple
print(fruits[1]) # Output: banana

Python lists also support negative indexing, which allows you to access items from the end of the list. The last item is at index -1, the second last is at index -2, and so on.

For example:

fruits = ["apple", "banana", "mango", "orange"]
print(fruits[-1]) # Output: orange
print(fruits[-2]) # Output: mango

Accessing Multiple Items With Slicing

Slicing allows you to retrieve a range of items from a list.

The basic syntax of list slicing is:

list[start:end:step]

where,

start (Optional): Index where the slice starts (inclusive). Defaults to 0, if omitted.

end (Optional): Index where the slice ends (exclusive). Defaults to the end of the list, if omitted.

step (Optional): The interval between items in the slice. Defaults to 1, if omitted.

For example:

fruits = ["apple", "banana", "mango", "orange"]
print(fruits[:3]) # Output: ['apple', 'banana', 'mango']

In this example, the start index is omitted, meaning the slicing will start from the index 0. The end index is 3, meaning the slicing will stop just before 3 (only includes items at index 0, 1, and 2, but not the item at index 3). Therefore, the resulting list includes the first three items: "apple", "banana", and "mango".

Here are more examples of list slicing:

fruits = ["apple", "banana", "mango", "orange", "pineapple"]

# Accessing elements from index 1 to 3
print(fruits[1:3]) # Output: ['banana', 'mango']

# Accessing all elements starting from index 2 (end index is omitted)
print(fruits[2:]) # Output: ['mango', 'orange', 'pineapple']

# Accessing all elements from start to end (both start and end index is omitted)
print(fruits[:]) # Output: ['apple', 'banana', 'mango', 'orange', 'pineapple']

# Accessing elements with a step of 2 (every second element)
print(fruits[::2]) # Output: ['apple', 'mango', 'pineapple']

Adding Items to a List

You can add items to a list in Python using three primary methods: using the append(), insert(), or extend() methods.

Using append()

The append() method adds a single item to the end of the list.

For example:

numbers = [5, 10, 15]

numbers.append(20)
print(numbers) # Output: [5, 10, 15, 20]

Using insert()

The insert() method adds an item at a specified index.

For example:

numbers = [5, 10, 15]

numbers.insert(1, 99)
print(numbers) # Output: [5, 99, 10, 15]

Using extend()

The extend() method adds multiple items from another iterable (like a list, tuple, or string) to the end of the current list.

For example:

numbers = [5, 10, 15]
another_list = [88, 99]

numbers.extend(another_list)
print(numbers) # Output: [5, 10, 15, 88, 99]

Change List Items

In Python, you can update a specific item in a list by assigning a new value to its index using square bracket notation.

For example:

fruits = ["apple", "banana", "mango"]

# Update the item at index 1
fruits[1] = "pineapple"
print(fruits) # Output: ['apple', 'pineapple', 'mango']

Change Multiple Items Using Slicing

You can update multiple items in a list at once by assigning new values to a slice of the list.

For example:

grades = [50, 60, 70, 80]

grades[1:3] = [90, 100]
print(grades) # Output: [50, 90, 100, 80]

Removing Items From a List

Here are the most common ways to remove items from a list in Python:

Using remove() – Remove by value

The remove() method removes the first occurrence of a specified value from the list.

For example:

numbers = [5, 10, 15, 5]
numbers.remove(5)
print(numbers) # Output: [10, 15, 5]

Using pop() – Remove by index

The pop() method removes and returns an item at a specified index from the list. If no index is specified, it removes and returns the last item.

For example:

numbers = [5, 10, 15, 20]

# Removes and returns the item at index 1
removed_value = numbers.pop(1)
print(removed_value) # Output: 10
print(numbers) # Output: [5, 15, 20]

# Removes and returns the last item
removed_value = numbers.pop()
print(removed_value) # Output: 20
print(numbers) # Output: [5, 15]

Using del Statement

The del statement removes an item at a specified index or slices of items.

For example:

fruits = ["apple", "banana", "mango", "orange", "pineapple"]

# Remove single item
del fruits[0]
print(fruits) # Output: ['banana', 'mango', 'orange', 'pineapple']

# Remove slice of items
del fruits[1:3]
print(fruits) # Output: ['banana', 'pineapple']

# Remove entire list
del fruits
# Trying to print list will raise an error since it is deleted
# print(fruits) 

Using clear()

The clear() method removes all items from the list, resulting in an empty list.

For example:

fruits = ["apple", "banana", "mango", "orange"]

fruits.clear()
print(fruits) # Output: []

List Length

You can get the length of a list (i.e., the number of items in a list) using the len() function.

For example:

fruits = ["apple", "banana", "mango", "orange"]
print(len(fruits)) # Output: 4

Iterating Through a List

You can iterate through a list in Python using a for loop.

For example:

fruits = ["apple", "banana", "mango", "orange"]

for fruit in fruits:
    print(fruit)

Output:

apple
banana
mango
orange

In this example, the for loop iterates over each item in the fruits list. On each iteration, the current item is stored in the variable fruit (you can name this variable anything you like), and the print(fruit) statement outputs them to the console. This process repeats until all the elements in the list have been printed.

The list() Constructor

The list() constructor converts the iterable (like a string, tuple, or another list) into a new list.

For example:

fruit_tuple = ("apple", "banana", "mango")
fruit_list = list(fruit_tuple)
print(fruit_list) # Output: ['apple', 'banana', 'mango']

Python List Methods

Python offers a variety of built-in methods to perform operations on lists. We have already covered methods like append(), insert(), extend(), remove(), pop(), and clear(). Now, let’s explore some other commonly used list methods:

index()

Returns the index of the first occurrence of a specified value.

For example:

fruits = ["apple", "banana", "mango", "banana"]
print(fruits.index("banana")) # Output: 1

count()

Returns the number of items the specified value appears in the list.

For example:

fruits = ["apple", "banana", "mango", "banana"]
print(fruits.count("banana")) # Output: 2

sort()

Sorts the list in ascending order by default. You can also sort in descending order using the reverse=True argument.

For example:

numbers = [50, 10, 30, 20, 40]

# Sort a list in ascending order
numbers.sort() 
print(numbers) # Output: [10, 20, 30, 40, 50]

# Sort a list in descending order
numbers.sort(reverse=True)
print(numbers) # Output: [50, 40, 30, 20, 10]

reverse()

Reverse the order of items in the list (in-place, not sorted).

For example:

numbers = [20, 10, 30]
numbers.reverse()
print(numbers) # Output: [30, 10, 20]

copy()

Returns a shallow copy of the list.

For example:

fruits = ["apple", "banana", "mango", "orange"]
copy_list = fruits.copy()
print(copy_list) # Output: ['apple', 'banana', 'mango', 'orange']

Note: Even though a shallow copy is a new list, it shares the same inner objects as the original list. So, changing a mutable item (e.g., list, dictionary, set) inside the shallow copy also affects the original list. However, changing an immutable item (e.g., integer, string, tuple) inside a shallow copy does not affect the original list.

Here is a table of all the list methods:

MethodDescription
append(item)Adds a single item to the end of the list.
pop(index)Removes and returns the item at the given index (default: last item).
remove(item)Removes the first occurrence of the specified item.
extend(iterable)Adds all elements from the given iterable (e.g. another list) to the end of the list.
sort()Sorts the list in ascending order.
reverse()Reverses the order of the list in-place.
insert(index, item)Inserts an item at the specified index.
index(item)Returns the index of the first occurrence of the specified item.
count(item)Counts the number of times the specified item appears in the list.
clear()Removes all the items from the list, leaving it empty.
copy()Creates a shallow copy of the list.