Python Lists as a Data Structure

Learn Python Lists as a Data Structure with practical examples, explanations, best practices, and real-world coding techniques.

A list in Python is an ordered, mutable collection used to store multiple values in a single variable. Lists are one of the most commonly used data structures in Python and are suitable for storing sequences of related data.

Python lists support indexing, slicing, insertion, deletion, searching, sorting, and iteration. A list can contain duplicate values and can hold objects of different types. Because lists are mutable, their contents can be changed after the list is created.

Creating a List in Python

Lists are created using square brackets. Elements are separated by commas.

languages = ["Python", "JavaScript", "Java"]

print(languages)

An empty list can be created when elements will be added later.

skills = []

skills.append("Python")
skills.append("SQL")
skills.append("Git")

print(skills)

List with Different Data Types

Python lists can contain values of different data types. They can also contain other collections such as dictionaries, tuples, and lists.

items = [
    "Python",
    100,
    True,
    25.5,
    {"name": "Alice"}
]

print(items)

Although mixed-type lists are supported, using a consistent element structure is often easier to understand and maintain in larger applications.

Accessing List Elements

Python lists use zero-based indexing. The first element has index 0, the second has index 1, and so on.

languages = ["Python", "JavaScript", "Java"]

print(languages[0])
print(languages[1])
print(languages[2])

Negative Indexing

Negative indexes access elements from the end of the list. -1 refers to the last element, -2 refers to the second-last element, and so on.

languages = ["Python", "JavaScript", "Java"]

print(languages[-1])
print(languages[-2])

Updating List Elements

Since lists are mutable, an element can be replaced by assigning a new value to its index.

languages = ["Python", "JavaScript", "Java"]

languages[1] = "TypeScript"

print(languages)

Updating an existing element changes its value without adding another element to the list.

Adding Elements to a List

append()

The append() method adds one element to the end of a list.

numbers = [10, 20, 30]

numbers.append(40)

print(numbers)

insert()

The insert() method adds an element at a specific index.

numbers = [10, 20, 30]

numbers.insert(1, 15)

print(numbers)

extend()

The extend() method adds all elements from another iterable to the end of the list.

frontend = ["HTML", "CSS"]
backend = ["Python", "SQL"]

frontend.extend(backend)

print(frontend)

Removing Elements from a List

remove()

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

numbers = [10, 20, 30, 20]

numbers.remove(20)

print(numbers)

If the specified value does not exist, remove() raises a ValueError.

pop()

The pop() method removes and returns an element. Without an index, it removes the last element.

numbers = [10, 20, 30]

removed = numbers.pop()

print("Removed:", removed)
print(numbers)

An index can also be supplied to remove an element from a specific position.

numbers = [10, 20, 30, 40]

removed = numbers.pop(1)

print("Removed:", removed)
print(numbers)

del

The del statement can remove an element or a range of elements from a list.

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

del numbers[1]

print(numbers)

del numbers[1:3]

print(numbers)

clear()

The clear() method removes all elements while keeping the list object available.

numbers = [10, 20, 30]

numbers.clear()

print(numbers)

Finding the Length of a List

Python's built-in len() function returns the number of elements in a list.

users = ["Alice", "Bob", "Charlie"]

print(len(users))

Searching a Python List

The in operator checks whether a value exists in a list.

languages = ["Python", "JavaScript", "Java"]

print("Python" in languages)
print("C#" in languages)

The index() method returns the index of the first matching value.

languages = ["Python", "JavaScript", "Java"]

position = languages.index("JavaScript")

print(position)

index() raises a ValueError when the value cannot be found, so use membership testing first when appropriate.

Counting List Elements

The count() method returns how many times a value occurs in a list.

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

print(numbers.count(10))
print(numbers.count(50))

Traversing a List

A for loop is the most common way to iterate over list elements.

languages = ["Python", "JavaScript", "Java"]

for language in languages:
    print(language)

Use enumerate() when both the index and value are required.

languages = ["Python", "JavaScript", "Java"]

for index, language in enumerate(languages):
    print(index, language)

List Slicing

Slicing creates a new list containing elements from a specified range. The general syntax is list[start:stop:step].

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

print(numbers[1:4])
print(numbers[:3])
print(numbers[2:])
print(numbers[::2])

The stop index is excluded from the resulting slice.

Reversing a List

The reverse() method reverses the existing list in place.

numbers = [10, 20, 30, 40]

numbers.reverse()

print(numbers)

Slicing can also create a reversed copy of a list.

numbers = [10, 20, 30, 40]

reversed_numbers = numbers[::-1]

print(reversed_numbers)
print(numbers)

Sorting a Python List

The sort() method sorts the existing list in place.

numbers = [40, 10, 30, 20]

numbers.sort()

print(numbers)

Use reverse=True for descending order.

numbers = [40, 10, 30, 20]

numbers.sort(reverse=True)

print(numbers)

sorted() vs sort()

The built-in sorted() function returns a new sorted list and leaves the original list unchanged.

numbers = [40, 10, 30, 20]

sorted_numbers = sorted(numbers)

print("Original:", numbers)
print("Sorted:", sorted_numbers)

List Concatenation

The + operator combines two lists into a new list.

frontend = ["HTML", "CSS"]
backend = ["Python", "SQL"]

technologies = frontend + backend

print(technologies)

Copying a Python List

Assigning one list variable to another does not create an independent list. Both variables refer to the same list object.

numbers = [10, 20, 30]

other = numbers

other.append(40)

print(numbers)
print(other)

To create a shallow copy, use copy() or slicing.

numbers = [10, 20, 30]

copy_one = numbers.copy()
copy_two = numbers[:]

copy_one.append(40)

print("Original:", numbers)
print("Copy:", copy_one)

A shallow copy creates a new outer list, but nested mutable objects are still shared. Use copy.deepcopy() when a deep copy is actually required.

List Comprehension

A list comprehension provides a concise way to create a list from an iterable, optionally applying a condition or transformation.

numbers = [1, 2, 3, 4, 5]

squares = [number * number for number in numbers]

print(squares)

A condition can be included to select only specific values.

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

even_numbers = [
    number
    for number in numbers
    if number % 2 == 0
]

print(even_numbers)

Nested Lists

A list can contain other lists. This is commonly used to represent tables, matrices, grids, and multidimensional data.

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(matrix[0][1])
print(matrix[2][2])

The first index selects the inner list, while the second index selects an element within that inner list.

Lists of Dictionaries

A common application pattern is storing multiple records as dictionaries inside a list.

users = [
    {"id": 1, "name": "Alice"},
    {"id": 2, "name": "Bob"},
    {"id": 3, "name": "Charlie"}
]

for user in users:
    print(user["name"])

Filtering a List

List comprehensions are often convenient for filtering values based on a condition.

scores = [45, 78, 92, 51, 88]

passing_scores = [
    score
    for score in scores
    if score >= 60
]

print(passing_scores)

Using a List as a Stack

Python lists can implement a stack efficiently when elements are added and removed from the end. The stack follows the LIFO principle.

stack = []

stack.append("A")
stack.append("B")
stack.append("C")

print(stack.pop())
print(stack.pop())

For stack behavior, append() and pop() operate at the end of the list.

Using a List as a Queue

A list can technically represent a queue, but repeatedly removing elements from the beginning with pop(0) requires shifting the remaining elements and can be inefficient.

queue = ["A", "B", "C"]

item = queue.pop(0)

print("Removed:", item)
print(queue)

For a queue that frequently adds and removes elements from both ends, Python's collections.deque is generally a better fit.

List Time Complexity

Python lists are dynamic arrays. Their typical operation costs are important when designing algorithms.

Operation Typical Complexity
Access by index O(1)
Update by index O(1)
append() O(1) amortized
pop() from end O(1)
insert() at beginning O(n)
pop(0) O(n)
Search with in O(n)
sort() O(n log n)
Traversal O(n)

The O(1) complexity of append() is amortized because a growing list may occasionally need to allocate a larger internal storage area.

List vs Tuple

Lists and tuples are both ordered sequences, but their mutability is different.

Feature List Tuple
Mutable Yes No
Syntax [] ()
Indexing Yes Yes
Typical use Changing collections Fixed collections

Common List Mistakes in Python

  • Forgetting that list indexes start at zero.
  • Using pop(0) repeatedly for a large queue.
  • Assuming assigning one list variable to another creates an independent copy.
  • Modifying a list while iterating over it without understanding the effect on iteration.
  • Using sort() when the original list should remain unchanged.
  • Confusing remove(), pop(), and del.
  • Accessing an invalid index and causing an IndexError.
  • Assuming a shallow copy also copies nested mutable objects.

Practical Example: Managing Product Prices

Lists are commonly used to collect and process application data. The following example filters product prices, applies a discount, and calculates the total.

prices = [499, 1200, 799, 2500, 999]

eligible_prices = [
    price
    for price in prices
    if price >= 800
]

discounted_prices = [
    price * 0.9
    for price in eligible_prices
]

total = sum(discounted_prices)

print("Eligible:", eligible_prices)
print("Discounted:", discounted_prices)
print("Total:", total)

Key Takeaways

  • Python lists are ordered and mutable collections.
  • List indexes start at zero and support negative indexing.
  • append(), insert(), and extend() are commonly used to add elements.
  • remove(), pop(), del, and clear() provide different ways to remove elements.
  • Lists support slicing, searching, sorting, reversing, and iteration.
  • List comprehensions provide a concise way to create transformed or filtered lists.
  • Lists can represent stacks efficiently using append() and pop().
  • Use collections.deque instead of repeated pop(0) operations for large queues.
  • Access by index is typically O(1), while searching and insertion at arbitrary positions are typically O(n).
  • Understanding list behavior and complexity is important for Python programming and algorithm design.

Code Examples

languages = ["Python", "JavaScript", "Java"]

languages.append("C#")
languages[1] = "TypeScript"

print(languages)
    
numbers = [10, 20, 40, 50]

numbers.insert(2, 30)

print(numbers)

removed = numbers.pop(1)

print("Removed:", removed)
print(numbers)
    
numbers = [1, 2, 3, 4, 5, 6]

squares = [
    number * number
    for number in numbers
]

even_numbers = [
    number
    for number in numbers
    if number % 2 == 0
]

print("Squares:", squares)
print("Even:", even_numbers)
    
languages = [
    "Python",
    "JavaScript",
    "Python",
    "Java"
]

print("Python" in languages)
print("Index:", languages.index("JavaScript"))
print("Python count:", languages.count("Python"))
    
scores = [45, 78, 92, 51, 88]

passing_scores = [
    score
    for score in scores
    if score >= 60
]

passing_scores.sort(reverse=True)

print(passing_scores)
    

Pro Tip

Use Python lists when you need an ordered, mutable collection with indexed access. For stack operations, append() and pop() at the end are efficient. For queue operations that remove from the front frequently, prefer collections.deque instead of repeatedly using pop(0).

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.