Python List Tutorial

Python List Tutorial

What is a Python List ?

A list is a built-in data structure in Python that stores an ordered collection of items. Lists are:

  • Mutable: You can change their contents after creation.
  • Ordered: Items maintain their order unless explicitly modified.
  • Heterogeneous: Can store different data types (e.g., integers, strings, objects).
  • Dynamic: Can grow or shrink in size.

Example of a list:

my_list = [1, "apple", 3.14, True]

Creating a List

You can create a list using square brackets [] or the list() constructor.

# Using square brackets
fruits = ["apple", "banana", "orange"]

# Using list() constructor
numbers = list((1, 2, 3, 4))

print(fruits)  # Output: ['apple', 'banana', 'orange']
print(numbers)  # Output: [1, 2, 3, 4]

Accessing List Elements

Lists are indexed starting from 0. You can access elements using their index or negative indexing for reverse access.

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

You can also use slicing to access a range of elements:

print(fruits[0:2])  # Output: ['apple', 'banana']
print(fruits[:])    # Output: ['apple', 'banana', 'orange']

Python List Methods

Below is a comprehensive list of Python list methods, each explained with an example.

1. append(x)

Adds an item x to the end of the list.

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

Explanation: The append() method adds a single element to the end of the list, increasing its length by 1.

2. extend(iterable)

Adds all elements from an iterable (e.g., list, tuple) to the end of the list.

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

Explanation: Unlike append(), which adds the iterable as a single element, extend() unpacks the iterable and adds each element individually.

3. insert(i, x)

Inserts an item x at a specified index i.

fruits = ["apple", "banana"]
fruits.insert(1, "orange")
print(fruits)  # Output: ['apple', 'orange', 'banana']

Explanation: The item is inserted at the given index, and all subsequent elements are shifted to the right. If the index is larger than the list length, the item is appended.

4. remove(x)

Removes the first occurrence of item x from the list.

fruits = ["apple", "banana", "apple"]
fruits.remove("apple")
print(fruits)  # Output: ['banana', 'apple']

Explanation: If the item is not found, a ValueError is raised. Only the first occurrence is removed.

5. pop([i])

Removes and returns the item at index i. If no index is specified, it removes and returns the last item.

fruits = ["apple", "banana", "orange"]
popped_item = fruits.pop()
print(popped_item)  # Output: orange
print(fruits)       # Output: ['apple', 'banana']

# Pop with index
popped_item = fruits.pop(0)
print(popped_item)  # Output: apple
print(fruits)       # Output: ['banana']

Explanation: Useful for removing items and using their values. Raises an IndexError if the list is empty or the index is out of range.

6. clear()

Removes all items from the list, leaving it empty.

fruits = ["apple", "banana", "orange"]
fruits.clear()
print(fruits)  # Output: []

Explanation: The list becomes empty but still exists as an object. Equivalent to del my_list[:].

7. index(x[, start[, end]])

Returns the index of the first occurrence of item x in the list, optionally within a start and end range.

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

Explanation: Raises a ValueError if the item is not found. Useful for finding the position of an element.

8. count(x)

Returns the number of occurrences of item x in the list.

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

Explanation: Counts how many times an item appears. Returns 0 if the item is not in the list.

9. sort(key=None, reverse=False)

Sorts the list in place, optionally using a key function for custom sorting and reverse=True for descending order.

numbers = [3, 1, 4, 1, 5]
numbers.sort()
print(numbers)  # Output: [1, 1, 3, 4, 5]

# Sort in descending order
numbers.sort(reverse=True)
print(numbers)  # Output: [5, 4, 3, 1, 1]

# Sort with key
fruits = ["apple", "banana", "cherry"]
fruits.sort(key=len)
print(fruits)  # Output: ['apple', 'cherry', 'banana']

Explanation: Modifies the list directly. The key parameter allows custom sorting (e.g., by length of strings).

10. reverse()

Reverses the order of the list in place.

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

Explanation: Changes the list’s order without sorting. Equivalent to my_list[::-1] but modifies the list in place.

11. copy()

Returns a shallow copy of the list.

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

Explanation: Creates a new list with the same elements. Changes to the copy do not affect the original list (for shallow copies).

Additional List Operations

1. List Concatenation

Combine lists using the + operator or +=.

list1 = [1, 2]
list2 = [3, 4]
combined = list1 + list2
print(combined)  # Output: [1, 2, 3, 4]

list1 += [5, 6]
print(list1)  # Output: [1, 2, 5, 6]

2. List Repetition

Repeat a list using the * operator.

numbers = [1, 2]
repeated = numbers * 3
print(repeated)  # Output: [1, 2, 1, 2, 1, 2]

3. Membership Testing

Check if an item exists in a list using in.

fruits = ["apple", "banana"]
print("apple" in fruits)  # Output: True
print("mango" in fruits)  # Output: False

4. List Length

Get the number of items using len().

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

Common Use Cases

Example 1: Managing a Shopping List

shopping_list = ["milk", "bread"]

# Add an item
shopping_list.append("eggs")
print(shopping_list)  # Output: ['milk', 'bread', 'eggs']

# Insert an item at index 1
shopping_list.insert(1, "butter")
print(shopping_list)  # Output: ['milk', 'butter', 'bread', 'eggs']

# Remove an item
shopping_list.remove("bread")
print(shopping_list)  # Output: ['milk', 'butter', 'eggs']

# Sort the list
shopping_list.sort()
print(shopping_list)  # Output: ['butter', 'eggs', 'milk']

Example 2: Filtering Numbers

numbers = [1, 2, 3, 4, 5, 6]
evens = [num for num in numbers if num % 2 == 0]  # List comprehension
print(evens)  # Output: [2, 4, 6]

Key Points

  • Lists are mutable, so methods like append(), remove(), and sort() modify the list in place.
  • Use copy() to avoid unintended changes when working with list copies.
  • Methods like index() and remove() raise errors if the item is not found, so handle exceptions if necessary.
  • List comprehensions (e.g., [x for x in list]) are a concise way to create new lists.

Scroll to Top