Skip to main content

Python Lists

Lists are one of the most versatile and commonly used data structures in Python. They allow you to store collections of items in an ordered sequence, and provide powerful ways to manipulate data.

Introduction to Lists

A list in Python is a collection of items that are ordered and changeable. Unlike strings, which are immutable, lists can be modified after creation. Lists can contain items of different data types, including numbers, strings, and even other lists.

Lists are defined by enclosing a comma-separated sequence of items in square brackets [].

Creating Lists

There are several ways to create a list in Python:

Empty List

python
# Creating an empty list
my_list = []
print(my_list)

Output:

[]

List with Initial Values

python
# Creating a list with initial values
fruits = ["apple", "banana", "cherry"]
print(fruits)

# List with mixed data types
mixed_list = [1, "Hello", 3.14, True]
print(mixed_list)

Output:

['apple', 'banana', 'cherry']
[1, 'Hello', 3.14, True]

Using the list() Constructor

python
# Creating a list using the list() constructor
numbers = list((1, 2, 3, 4, 5))
print(numbers)

# Converting a string to a list of characters
chars = list("Python")
print(chars)

Output:

[1, 2, 3, 4, 5]
['P', 'y', 't', 'h', 'o', 'n']

Accessing List Elements

List items are indexed, and you can access them by referring to their index number:

python
fruits = ["apple", "banana", "cherry", "orange", "kiwi"]

# Accessing by positive index (0-based)
print(fruits[0]) # First item
print(fruits[2]) # Third item

# Accessing by negative index (counts from the end)
print(fruits[-1]) # Last item
print(fruits[-3]) # Third last item

Output:

apple
cherry
kiwi
cherry

List Slicing

You can extract a section of a list using slicing:

python
fruits = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]

# Syntax: list[start:end:step]
# start is included, end is excluded

# Get items from index 1 to 3 (excluding 4)
print(fruits[1:4])

# From beginning to index 3 (excluding 4)
print(fruits[:4])

# From index 2 to the end
print(fruits[2:])

# Every second item from the entire list
print(fruits[::2])

# Reversing a list
print(fruits[::-1])

Output:

['banana', 'cherry', 'orange']
['apple', 'banana', 'cherry', 'orange']
['cherry', 'orange', 'kiwi', 'mango']
['apple', 'cherry', 'kiwi']
['mango', 'kiwi', 'orange', 'cherry', 'banana', 'apple']

Modifying Lists

Lists are mutable, which means you can change their content after creation.

Changing Items

python
fruits = ["apple", "banana", "cherry"]

# Change the second item
fruits[1] = "blueberry"
print(fruits)

Output:

['apple', 'blueberry', 'cherry']

Adding Items

python
fruits = ["apple", "banana", "cherry"]

# Add item to the end of the list
fruits.append("orange")
print(fruits)

# Insert item at a specific position
fruits.insert(1, "mango") # Insert at index 1
print(fruits)

# Extend the list by appending elements from another list
more_fruits = ["kiwi", "grape"]
fruits.extend(more_fruits)
print(fruits)

Output:

['apple', 'banana', 'cherry', 'orange']
['apple', 'mango', 'banana', 'cherry', 'orange']
['apple', 'mango', 'banana', 'cherry', 'orange', 'kiwi', 'grape']

Removing Items

python
fruits = ["apple", "banana", "cherry", "banana", "kiwi"]

# Remove a specific item
fruits.remove("banana") # Removes the first occurrence
print(fruits)

# Remove item at specific index
popped_fruit = fruits.pop(1) # Removes and returns item at index 1
print(f"Removed: {popped_fruit}")
print(fruits)

# Remove the last item
last_fruit = fruits.pop()
print(f"Last item removed: {last_fruit}")
print(fruits)

# Clear the list (remove all items)
fruits.clear()
print(fruits)

Output:

['apple', 'cherry', 'banana', 'kiwi']
Removed: cherry
['apple', 'banana', 'kiwi']
Last item removed: kiwi
['apple', 'banana']
[]

List Operations

List Concatenation

python
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]

# Combining lists with +
combined_list = list1 + list2
print(combined_list)

Output:

['a', 'b', 'c', 1, 2, 3]

List Repetition

python
# Repeating a list with *
repeated_list = list1 * 3
print(repeated_list)

Output:

['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']

Finding List Length

python
fruits = ["apple", "banana", "cherry", "orange", "kiwi"]
print(f"The list contains {len(fruits)} items")

Output:

The list contains 5 items

Common List Methods

Python provides many built-in methods to work with lists:

python
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]

# Sorting a list
numbers.sort()
print(f"Sorted: {numbers}")

# Reversing a list
numbers.reverse()
print(f"Reversed: {numbers}")

# Count occurrences of an item
ones = numbers.count(1)
print(f"Count of 1's: {ones}")

# Find index of first occurrence
index_of_5 = numbers.index(5)
print(f"Index of first 5: {index_of_5}")

Output:

Sorted: [1, 1, 2, 3, 4, 5, 5, 6, 9]
Reversed: [9, 6, 5, 5, 4, 3, 2, 1, 1]
Count of 1's: 2
Index of first 5: 2

List Comprehensions

List comprehensions provide a concise way to create lists. They consist of an expression followed by a for statement inside square brackets.

python
# Create a list of squares
squares = [x**2 for x in range(1, 6)]
print(squares)

# List comprehension with condition
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print(even_squares)

Output:

[1, 4, 9, 16, 25]
[4, 16, 36, 64, 100]

Nested Lists (Lists within Lists)

Lists can contain other lists, creating multi-dimensional structures:

python
# 2D list (matrix)
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

print(matrix)

# Accessing elements in a 2D list
print(f"Second row: {matrix[1]}")
print(f"Element at row 2, column 3: {matrix[1][2]}")

# Processing all elements in a 2D list
for row in matrix:
for element in row:
print(element, end=" ")
print() # New line after each row

Output:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Second row: [4, 5, 6]
Element at row 2, column 3: 6
1 2 3
4 5 6
7 8 9

Practical Applications of Lists

Lists are incredibly versatile and used in many scenarios. Here are some practical applications:

To-Do List Application

python
# Simple To-Do List manager

# Initialize the list
tasks = []

# Add tasks
tasks.append("Buy groceries")
tasks.append("Complete Python assignment")
tasks.append("Go to the gym")

# Display tasks
print("Your To-Do List:")
for i, task in enumerate(tasks, 1):
print(f"{i}. {task}")

# Mark a task as completed (remove it)
completed_task_index = 1 # Complete the second task
completed = tasks.pop(completed_task_index)
print(f"\nCompleted: {completed}")

# Updated list
print("\nRemaining tasks:")
for i, task in enumerate(tasks, 1):
print(f"{i}. {task}")

Output:

Your To-Do List:
1. Buy groceries
2. Complete Python assignment
3. Go to the gym

Completed: Complete Python assignment

Remaining tasks:
1. Buy groceries
2. Go to the gym

Data Analysis Example

python
# Simple data analysis of student scores

scores = [85, 90, 78, 92, 88, 76, 95, 89, 84, 91]

# Basic statistics
total_students = len(scores)
highest_score = max(scores)
lowest_score = min(scores)
average_score = sum(scores) / total_students

print(f"Class Statistics:")
print(f"Total Students: {total_students}")
print(f"Highest Score: {highest_score}")
print(f"Lowest Score: {lowest_score}")
print(f"Average Score: {average_score:.2f}")

# Count students with scores above 90
high_performers = [score for score in scores if score >= 90]
print(f"Students with score 90 or above: {len(high_performers)}")

# Sort scores in descending order
sorted_scores = sorted(scores, reverse=True)
print(f"Scores (highest to lowest): {sorted_scores}")

Output:

Class Statistics:
Total Students: 10
Highest Score: 95
Lowest Score: 76
Average Score: 86.80
Students with score 90 or above: 4
Scores (highest to lowest): [95, 92, 91, 90, 89, 88, 85, 84, 78, 76]

Summary

Python lists are fundamental data structures that offer immense flexibility in storing and manipulating collections of data. In this guide, we've covered:

  • Creating lists in various ways
  • Accessing and modifying list elements
  • List operations and common methods
  • List comprehensions for creating lists concisely
  • Working with nested lists
  • Practical applications of lists

Lists are the foundation of many Python programs and understanding them well is crucial for effective Python programming. As you progress in your Python journey, you'll find lists indispensable for solving a wide range of problems.

Additional Resources and Exercises

Exercises

  1. List Manipulation: Create a program that takes a list of numbers and returns a new list containing only the even numbers.
  2. Shopping List Manager: Build a simple shopping list application that allows adding, removing, and viewing items.
  3. Matrix Operations: Write functions to add and multiply two matrices represented as nested lists.
  4. List Sorting Challenge: Create a function that sorts a list of strings by their length, then alphabetically for strings of the same length.

Further Reading

Remember that mastering lists will significantly enhance your ability to write efficient and effective Python programs!



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)