Back to Python
2026-03-235 min read

Python Lists Basics

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

Title: Python Lists Basics - A full guide for Practical Depth

Why This Matters

Understanding Python lists is crucial for anyone looking to excel in programming, whether you're a beginner or an experienced coder. Lists are fundamental data structures that allow us to store multiple items of the same type and perform various operations on them. In this lesson, we will delve into the world of Python lists, exploring their practical uses, common mistakes, and best practices for working with them.

Prerequisites

To fully grasp the concepts discussed in this lesson, you should have a basic understanding of Python syntax and programming fundamentals. Familiarity with variables, operators, control structures, and functions will be beneficial as we dive into more complex list operations.

Basic Python Syntax Review

  • Variables: A named storage location for data in Python.
  • Operators: Symbols that perform specific mathematical or logical operations on values.
  • Control Structures: Statements that control the flow of execution in a program, such as if, for, and while statements.
  • Functions: Reusable blocks of code that perform specific tasks.

Core Concept

What is a List?

In Python, a list is a collection of items that are ordered and mutable. It can contain elements of different data types, such as integers, strings, or even other lists. Lists are defined using square brackets [], and each item is separated by a comma. For example:

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

List Operations

Python provides various built-in functions to work with lists efficiently. Some of the most commonly used operations are:

  1. Accessing elements: You can access individual items in a list using their index number, which starts at 0 for the first item. For example:
print(my_list[0]) # Output: 1
print(my_list[2]) # Output: 3.14
  1. Adding elements: To add an element to a list, you can use the append() method or simply assign a new value to the list:
my_list.append("grape")
my_list = my_list + ["kiwi"]
  1. Removing elements: You can remove an element from a list using the remove() method or the del keyword:
my_list.remove("banana")
del my_list[1]
  1. Slicing: Lists in Python can be sliced to extract a portion of the original list. The syntax for slicing is as follows: list[start:end:step]. For example:
print(my_list[1:3]) # Output: ['apple', 3.14]
  1. List methods: Python offers several built-in methods for lists, such as sort(), reverse(), and count(). For example:
my_list.sort()
print(my_list) # Output: [1, "apple", 3.14, ["banana", "orange"], "grape", "kiwi"]

List Comprehensions

List comprehensions are a concise way to create and manipulate lists in Python. They allow you to perform operations on existing lists or generate new lists based on rules defined within the comprehension. For example:

Creating a list of squares from 1 to 10 using a list comprehension

squares = [i2 for i in range(1, 11)]

print(squares) # Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Worked Example

Let's work through an example to better understand how lists operate in Python. Suppose we have a list of student scores and want to find the average score.

scores = [85, 90, 77, 88, 92]
total_score = sum(scores)
average_score = total_score / len(scores)
print("Average Score:", average_score)

In this example, we first define a list of student scores. We then calculate the total score by using the built-in sum() function and find the average score by dividing the total score by the number of elements in the list (len(scores)). The output will be:

Average Score: 85.2

Common Mistakes

  1. Forgetting to initialize a list: It is essential to create an empty list before adding items to it:
my_list = [] # Correct
scores = # Incorrect
  1. Indexing out of range: Always ensure that the index you are using is within the bounds of the list:
print(my_list[3]) # Correct if my_list has at least 4 elements
print(my_list[10]) # Incorrect, as the list only contains up to 9 elements
  1. Modifying a loop variable: When using a for loop to iterate over a list, avoid modifying the loop variable within the loop body:
numbers = [1, 2, 3, 4, 5]
for i in numbers:
i = i * 2 # Incorrect; this will only change the value of 'i' for the current iteration, not the list itself

for i, number in enumerate(numbers):
numbers[i] = number * 2 # Correct; this modifies the original list
  1. Improper use of in and not in: Remember that in and not in operators check if a value is present or absent within the list, not its index:
if 3 in my_list: # Correct; checks if 3 is an element in my_list
print("Three is in the list.")

if 10 == my_list[3]: # Incorrect; checks if the fourth element's value is exactly 10, not whether it is the index 10
print("The fourth element is 10.")

Practice Questions

  1. Write a Python script that takes user input as a list of integers and finds the sum of all even numbers.
  2. Given a list of strings, write a function to sort the list alphabetically while preserving the case (i.e., both uppercase and lowercase letters should be sorted together).
  3. Write a Python script that removes duplicates from a given list without using any built-in functions.
  4. Write a function that finds all permutations of a given list of unique integers.
  5. Write a function that checks if a given list is a palindrome (reads the same forwards and backwards).

FAQ

  1. What happens if I try to add an element of a different data type to a list containing only integers?
  • When you try to add an item of a different data type to a homogeneous list, Python will append the new item as it is. However, if you want to ensure that all items in the list are of the same type, you can use the map() function or convert the new item to the appropriate data type before appending it.
  1. Can I create a list with nested lists?
  • Yes! Lists in Python can contain other lists as elements, allowing for complex data structures. For example:
nested_list = [1, 2, [3, 4], 5]
  1. How do I check if a list is empty before performing any operations on it?
  • You can use the if not my_list: conditional to check if a list is empty:
if not my_list:
print("The list is empty.")
else:

Perform operations on the list


4. **What are some best practices for working with lists in Python?**
- Some best practices include:
- Initializing lists before using them to avoid errors.
- Using list comprehensions for efficient list creation and manipulation.
- Avoiding modifying a loop variable within the loop body when iterating over a list.
- Checking if a list is empty before performing operations on it to prevent errors.
- Using appropriate data types for each element in the list to maintain consistency and avoid unexpected behavior.
Python Lists Basics | Python | XQA Learn