Back to Python
2025-12-206 min read

Python Lists

Learn Python Lists step by step with clear examples and exercises.

Why This Matters

In this tutorial, we will delve into one of the most fundamental data structures in Python - Lists. We'll cover why lists matter in programming, prerequisites, core concepts, a worked example, common mistakes, practice questions, and frequently asked questions. By the end of this lesson, you'll have a strong understanding of Python lists, enabling you to tackle real-world coding challenges with confidence.

Why Lists Matter

Lists are essential in programming as they allow us to store multiple items of different data types in a single variable. They are versatile and widely used for various purposes such as storing collections of numbers, strings, or even other lists. Lists also play a crucial role in solving complex problems, debugging code, and preparing for interviews.

Prerequisites

Before diving into Python lists, it is essential to have a good understanding of the following topics:

  • Variables and data types in Python
  • Basic arithmetic operations and data manipulation
  • Control structures (if-else statements and loops)
  • Basic file handling (for reading files)

Understanding Data Types

In Python, lists are a type of compound data structure that can hold items of different data types. Familiarize yourself with the basic data types in Python:

  • Integers (e.g., 1, 42)
  • Floating-point numbers (e.g., 3.14, -0.5)
  • Strings (e.g., "Hello", 'World')
  • Booleans (True, False)
  • Tuples (immutable lists)
  • Dictionaries (key-value pairs)

Core Concept

Definition and Syntax

A list in Python is a collection of items enclosed within square brackets []. Each item can be of any data type, and items are separated by commas. Here's an example:

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

In this example, my_list is a list containing an integer, a string, a float, another list, and a boolean value.

Accessing List Items

To access an item in a list, use its index number within the square brackets. Python uses zero-based indexing, so the first item has an index of 0:

print(my_list[0]) # Output: 1
print(my_list[3][1]) # Output: orange

Modifying List Items

To modify a list item, simply assign a new value to the index of the desired item:

my_list[0] = "one"
print(my_list) # Output: ['one', 'apple', 3.14, ['banana', 'orange'], True]

Adding Items to a List

To add an item to the end of a list, use the append() method:

my_list.append("grape")
print(my_list) # Output: ['one', 'apple', 3.14, ['banana', 'orange'], True, 'grape']

Inserting Items at a Specific Position

Use the insert() method to add an item at a specific position in the list. The first argument is the index where you want to insert the item, and the second argument is the value:

my_list.insert(1, "two")
print(my_list) # Output: ['one', 'two', 'apple', 3.14, ['banana', 'orange'], True, 'grape']

Removing Items from a List

To remove an item by its index, use the remove() method:

my_list.remove("two")
print(my_list) # Output: ['one', 'apple', 3.14, ['banana', 'orange'], True, 'grape']

Slicing Lists

To extract a portion of a list, use slicing syntax with square brackets and colons:

print(my_list[1:3]) # Output: ['apple', 3.14]

Sorting and Reversing Lists

Use the sort() method to sort a list in ascending order, or sort(reverse=True) for descending order:

my_list.sort(reverse=True)
print(my_list) # Output: ['grape', True, ['banana', 'orange'], 3.14, 'apple', 'one']

List Comprehensions

List comprehensions allow you to create new lists based on existing ones using a concise syntax. Here's an example:

numbers = [1, 2, 3, 4, 5]
squares = [number ** 2 for number in numbers]
print(squares) # Output: [1, 4, 9, 16, 25]

Worked Example

Let's create a simple program that calculates the average of numbers in a list and finds the largest number:

numbers = [5, 7, 2, 9, 6]
total = sum(numbers)
average = total / len(numbers)
print("The average is:", average)

largest_number = max(numbers)
print("The largest number is:", largest_number)

In this example, we first define a list of numbers. We then use the built-in sum() function to calculate the total of all numbers in the list. To find the average, we divide the total by the length of the list (number of items). To find the largest number, we use the built-in max() function. Finally, we print both calculated values.

Common Mistakes

  1. Forgetting commas between items: Remember that each item in a list should be separated by a comma.
  2. Accessing out-of-range indices: Be aware of the index numbers when accessing or modifying list items to avoid out-of-range errors.
  3. Modifying a loop variable within a loop: If you modify a loop variable (such as an index) inside a loop, Python may not behave as expected. Use a separate variable for loop control and iteration.
  4. Misunderstanding slicing syntax: Make sure to understand the correct usage of slicing when extracting or modifying portions of lists.
  5. Not handling empty lists: Be aware that some list methods, such as max() and min(), may not work with empty lists.
  6. Using inappropriate data structures: Consider using other data structures like tuples for immutable collections or dictionaries for key-value pairs when appropriate.

Practice Questions

  1. Write a program that finds the largest number in a list and the smallest number in a list separately.
  2. Create a list containing the names of your favorite programming languages, sort them alphabetically, and print them in reverse order.
  3. Given a list of numbers, write a function that returns the sum of all even numbers and the sum of all odd numbers.
  4. Write a program that removes duplicates from a list without using any built-in Python functions.
  5. Create a list of tuples containing student names and their scores in an exam. Sort the list based on scores, and print the names and scores of students who scored above 80.
  6. Write a program that finds the position of the first occurrence of a specific value in a list using binary search (hint: use the built-in bisect module).
  7. Given two lists of numbers, write a function that returns a new list containing only the common elements between the two input lists.
  8. Write a program that finds the second largest number in a list (consider handling cases where the list has fewer than 2 unique elements).
  9. Create a list of dictionaries representing student records with attributes like name, age, and GPA. Sort the list based on GPA, and print the students with a GPA above 3.5.
  10. Write a program that finds all permutations of a given string (hint: use recursion or itertools).

FAQ

  1. Can I have empty lists in Python?

Yes, you can create an empty list using [].

  1. What happens if I try to access an index that doesn't exist in a list?

If you access an index that doesn't exist in the list, Python will raise an IndexError.

  1. Can I mix data types within a single list?

Yes, you can store items of different data types within a single list in Python. However, be aware that some operations may not work as expected when dealing with mixed data types.

  1. What are some common built-in functions for working with lists in Python?

Some commonly used built-in functions for lists include append(), insert(), remove(), sort(), reverse(), count(), and index(). Additionally, the len() function can be used to find the length of a list.

  1. How can I check if a list contains a specific value without using the in keyword?

You can use the count() function to find the number of occurrences of a specific value in a list, or loop through the list and check each item manually.

  1. Is there a way to create a list with predefined values using a single line of code?

Yes, you can create a list with predefined values using a single line of code called a list comprehension. For example: [1, 2, 3, 4, 5] = [i for i in range(1, 6)].

  1. What is the time complexity of common list operations in Python?
  • Accessing an element by index: O(1)
  • Insertion or deletion at the beginning or end: O(n)
  • Insertion or deletion in the middle: O(n) (amortized)
  • Slicing: O(n) (worst case)
  • Sorting: O(n log n) (best case O(n))
  • Searching for an element: O(n) (average and worst case)
Python Lists | Python | XQA Learn