Skip to content
Français
Account: not signed in, sync available My learning
Select theme
Français
Lire en français

Python lists: create, loop, sort (append, index)

32 min read
Improve this page

Logo Python

A list in Python is an ordered, modifiable collection of items, created with square brackets: groceries = ["bread", "milk", "eggs"]. It stores several values in a single variable, of any type (numbers, strings, objects, even other lists), and you can add, remove or modify its elements at any time. It is one of the most used data structures in Python.

This guide, for beginner and intermediate developers, covers creation, access by index, looping, the essential methods (append, sort, index) and list comprehensions.

What you will learn

  • Create a list that is empty, pre-filled or generated with range()
  • Access elements by index, negative index and slicing
  • Add and remove with append, insert, extend, remove, pop, del
  • Loop over a list with for, enumerate() and while
  • Find, count and sort with index, count, sort and sorted
  • Transform a list with comprehensions and handle nested lists

Why use lists?

Lists are ideal for storing sequences of related items, such as tracking information for a project, a shopping list, or sensor data in an IoT application. In Python they are simple to handle and intuitive, which makes them a natural choice for beginners.

Create and initialize a list

Creating a list in Python is very simple. Lists are defined by surrounding the items with square brackets []. These items can be of any type: integers, strings, booleans, even other lists, which makes Python lists very flexible.

Create an empty list

To create a list with no items, simply use empty square brackets []:

my_list = []

This initializes an empty list, ready to be filled. An empty list can be useful in many situations, for example when you want to collect items one by one in a loop.

Create a list with initial values

You can also initialize a list with predefined values:

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

In this example, my_list contains five items of type integer. This method is ideal when you already know the items to add.

Create a list with items of different types

A Python list can contain items of various types, which lets you nest data of different types in the same collection:

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

Here the list contains an integer, a string, a boolean and a floating-point number. This flexibility lets you group diverse data in a single variable.

Generate values automatically with range()

If you need a sequence of numbers, you can use the range() function, often combined with list(). For example, to create a list of numbers from 0 to 9:

my_list = list(range(10))

The range() function generates a sequence of numbers that list() converts into a list.

Access the elements of a list

Once a list is created, you need to know how to access its elements to use or modify them. Python lists use indexing to access each element.

Basic indexing

Lists are indexed sequences in Python, which means each element has a position in the list, called an index. Indexing starts at 0, so the first element of a list is at index 0, the second at index 1, and so on.

my_list = [10, 20, 30, 40, 50]
print(my_list[0]) # Prints 10
print(my_list[2]) # Prints 30

Using negative indexing

Python also lets you access the elements of a list with negative indices, which is particularly useful to reach elements from the end of the list. Index -1 is the last element, -2 the second to last, and so on.

print(my_list[-1]) # Prints 50
print(my_list[-2]) # Prints 40

Extract a sublist with slicing

Slicing selects a part of the list (a sublist). This technique is particularly useful to get a series of elements located at consecutive indices.

sublist = my_list[1:4]
print(sublist) # Prints [20, 30, 40]

Using the step in slicing

By adding a third argument to the slice, you can specify a step to skip elements.

sublist = my_list[0:5:2]
print(sublist) # Prints [10, 30, 50]

With the slice my_list[0:5:2], you select the elements of the list by skipping every other one.

Add and remove elements

Python offers several methods to add or remove elements from a list, which makes modifying it very flexible.

Add an element with append()

The append() method adds an element at the end of the list:

my_list.append(60)
print(my_list) # Prints [10, 20, 30, 40, 50, 60]

Insert an element at a specific position with insert()

To insert an element at a precise position, use insert(index, element):

my_list.insert(1, 15)
print(my_list) # Prints [10, 15, 20, 30, 40, 50, 60]

Add several elements with extend()

To add several elements at once, extend() is ideal:

my_list.extend([70, 80])
print(my_list) # Prints [10, 15, 20, 30, 40, 50, 60, 70, 80]

Remove an element with remove()

The remove() method removes the first occurrence of an element:

my_list.remove(15)
print(my_list) # Prints [10, 20, 30, 40, 50, 60, 70, 80]

Remove an element with pop()

pop() removes an element at a given position and returns it. If no index is given, it removes and returns the last element:

last_element = my_list.pop()
print(last_element) # Prints 80
print(my_list) # Prints [10, 20, 30, 40, 50, 60, 70]

Remove an element with del

The del statement removes an element by its index, or even a group of elements with slicing:

del my_list[0]
print(my_list) # Prints [20, 30, 40, 50, 60, 70]
del my_list[1:3]
print(my_list) # Prints [20, 50, 60, 70]

Modify the elements of a list

Lists in Python are modifiable (or mutable), which means you can change the value of existing elements.

Modify a specific element

To modify an element, access its position with its index and assign it a new value:

my_list[1] = 45
print(my_list) # Prints [20, 45, 60, 70]

Modify several elements with slicing

You can use slicing to modify several elements at once:

my_list[1:3] = [35, 55]
print(my_list) # Prints [20, 35, 55, 70]

Add or remove elements with slicing

Slicing also lets you add or remove elements in a single operation:

my_list[2:2] = [40, 50]
print(my_list) # Prints [20, 35, 40, 50, 55, 70]

Here, 40 and 50 are inserted at index 2.

Useful built-in functions for lists

Python offers many built-in functions to handle lists efficiently. These functions let you get information about a list or perform common operations such as counting, sorting or reversing elements.

List length with len()

The len() function returns the number of elements in a list, which can be handy in loops or to check whether a list is empty:

my_list = [10, 20, 30, 40, 50]
print(len(my_list)) # Prints 5

Here, len(my_list) returns 5 because the list contains five elements.

Find the position of an element with index()

The index() method finds the first position of a specific element in a list. If the element is not found, Python raises a ValueError:

position = my_list.index(30)
print(position) # Prints 2

In this example, index() returns 2 because the element 30 is at index 2 in the list.

Check whether an element is present with in

You can use the in operator to check whether an element exists in a list. It returns True if the element is found and False otherwise:

print(20 in my_list) # Prints True
print(60 in my_list) # Prints False

Count the occurrences of an element with count()

The count() method counts the number of occurrences of a specific element in the list. It can be useful to analyze data or to find duplicates:

my_list = [10, 20, 20, 30, 20]
print(my_list.count(20)) # Prints 3

In this example, count() returns 3 because the number 20 appears three times in the list my_list.

Sort a list with sort()

The sort() method sorts the elements of a list in ascending order by default, but it can also sort in descending order with the reverse=True argument:

my_list = [30, 10, 20, 50, 40]
my_list.sort()
print(my_list) # Prints [10, 20, 30, 40, 50]
my_list.sort(reverse=True)
print(my_list) # Prints [50, 40, 30, 20, 10]

Sorting is done in place, which means the original list is modified. If you want to keep the initial list, use the sorted() function to create a new sorted list.

Reverse a list with reverse()

The reverse() method reverses the order of the elements in a list. Unlike sort(), this method does not sort: it simply puts the elements in the opposite order:

my_list.reverse()
print(my_list) # Prints [10, 20, 30, 40, 50] (the list was [50, 40, 30, 20, 10])

Loops and iterations over a list

Looping over the elements of a list is a frequent operation in Python, especially to apply operations to each element. This section shows you how to use loops to go through the elements of a list.

Loop over a list with a for loop

The simplest and most common way to loop over a list is to use a for loop. It lets you access each element of the list:

my_list = [10, 20, 30, 40, 50]
for element in my_list:
print(element)

In this example, each element of my_list is printed one by one. It is the preferred method for simple operations.

Use enumerate() to get the indices and the elements

Sometimes you need the index of each element in addition to its value. In that case, use the enumerate() function, which gives you both the index and the element:

for index, element in enumerate(my_list):
print(f"Index {index}: {element}")

enumerate() returns index, value pairs for each element of the list, which is handy when the position of the element matters for the processing.

Loop over a list with a while loop

Another way to loop over a list is to use a while loop. It can be useful if you want to go through the list until a specific condition is met:

index = 0
while index < len(my_list):
print(my_list[index])
index += 1

Here we use a counter index to access the elements of my_list until all the elements have been visited.

Nested lists (lists of lists)

Nested lists are lists that contain other lists as elements. They let you build more complex data structures, such as matrices or multidimensional tables.

Create a nested list

To create a nested list, just include sublists inside a main list:

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

Here, my_list is a list of three sublists, each containing three elements.

Access the elements of a nested list

To access the elements of a nested list, you use two levels of indexing. The first index selects the sublist, the second selects the element within that sublist.

print(my_list[0]) # Prints [1, 2, 3]
print(my_list[0][1]) # Prints 2

In this example, my_list[0] returns the first sublist [1, 2, 3], and my_list[0][1] returns the second element of that sublist, that is 2.

Loop over a nested list with loops

To go through all the elements of a nested list, use nested loops: a first loop to go through the sublists and a second one to go through the elements of each sublist.

for sublist in my_list:
for element in sublist:
print(element)

Each sublist is traversed in the outer loop and each element in the inner loop.

Use list comprehensions with nested lists

List comprehensions can be nested to handle nested lists concisely. For example, to flatten a nested list into a simple list:

nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flat = [element for sublist in nested_list for element in sublist]
print(flat) # Prints [1, 2, 3, 4, 5, 6, 7, 8]

In this example, each element is extracted from each sublist to create a flattened list, flat.

List comprehensions

List comprehensions let you create new lists in a concise and readable way. They are particularly useful for quick transformations or filtering.

Basic syntax of list comprehensions

The basic syntax of a list comprehension is an expression followed by a for loop. For example, to create a list of the squares of the elements of an existing list:

my_list = [1, 2, 3, 4, 5]
squares = [x ** 2 for x in my_list]
print(squares) # Prints [1, 4, 9, 16, 25]

Use conditions in list comprehensions

List comprehensions can include conditions to filter the elements:

evens = [x for x in my_list if x % 2 == 0]
print(evens) # Prints [2, 4]

Here, only the even elements of my_list are included in the new list evens.

Nested list comprehensions

Nested list comprehensions let you handle nested lists concisely. For example, to get the squares of the elements of a nested list:

nested_list = [[1, 2], [3, 4]]
squares = [[x ** 2 for x in sublist] for sublist in nested_list]
print(squares) # Prints [[1, 4], [9, 16]]

Each sublist is traversed to compute the squares of its elements.

Advanced list methods

Finally, Python offers advanced methods to copy, merge and transform lists efficiently, notably with map() and filter().

Copy a list

To create a copy of a list, you can use copy() or the slice [:]. This avoids modifying the original list by accident:

my_list = [1, 2, 3]
list_copy = my_list.copy()

Merge lists

To merge two lists, use the + operator or the extend() method. The difference matters: + builds a new list and leaves both originals intact, whereas extend() modifies the list you call it on.

list1 = [1, 2]
list2 = [3, 4]
merged = list1 + list2
print(merged) # Prints [1, 2, 3, 4]

Use map() and filter()

map() applies a function to each element of a list, while filter() selects the elements that meet a condition:

my_list = [1, 2, 3]
squares = list(map(lambda x: x ** 2, my_list))
evens = list(filter(lambda x: x % 2 == 0, my_list))

Exercise: Managing a Shopping List

This exercise brings together all the previous notions in a single program: creation, append, remove, index, looping with enumerate() and splitting the code into functions. The first tab holds the problem statement to tackle on your own, the second a complete, step-by-step solution. Write your own version before reading the solution: the point of the exercise lies in the attempt.

Problem

This exercise guides you step by step through creating a Python program that manages a shopping list. You will learn to use basic list operations, loops, conditions and functions to build a small command-line application.

Goal: build an interactive Python program that lets you add, remove, edit and view the items of a shopping list.

Step 1: Initialize the List

The program must be able to start empty or with several items entered at once, separated by commas.

  1. Create an empty list named shopping_list to store the items.
  2. Ask the user whether they want to start with a list of items. If they answer "yes", invite them to enter items separated by commas. Use the appropriate method to add these items to shopping_list.
  3. Display the initial list of items, whether they were added or not.

Step 2: Add an Item

Adding always happens at the end of the list, and the user must see the result without having to ask for the display again.

  1. Ask the user to enter an item to add to the list.
  2. Add this item to the shopping_list list.
  3. Display a message confirming that the item was added and show the updated list.

Step 3: Remove an Item

An item that is requested but absent from the list is a normal case of use, not an error that must interrupt the program.

  1. Ask the user which item they want to remove from the list.
  2. Check that this item is in shopping_list. If it is, remove it. Otherwise, display a message saying the item is not in the list.
  3. Display the updated list after each removal.

Step 4: Edit an Item

Editing means replacing a value at the position it already occupies: the order of the list must not change.

  1. Ask the user which item they want to edit.
  2. Check that this item is in shopping_list. If it is, ask the user to enter the new value for this item and update the list.
  3. Display the updated list after each edit.

Step 5: Show the List

The display is meant for a human: numbering therefore starts at 1, whereas Python indices start at 0.

  1. Add an option that lets the user display the complete shopping list.
  2. Format the display so that each item is preceded by its number (e.g. "1. Bread", "2. Milk", etc.).

Step 6: Interactive Menu

The menu turns the previous actions into a usable program: it is displayed again after each operation and only stops on explicit request.

  1. Add a main menu that shows the following options:
    • "1: Show the shopping list"
    • "2: Add an item"
    • "3: Remove an item"
    • "4: Edit an item"
    • "5: Quit"
  2. Make the program repeat this menu after each action, until the user chooses to quit.

Step 7: Handle Input Errors

Everything that comes from input() is unpredictable. An unknown item or an invalid menu choice must produce a message, never a sudden stop of the program.

  1. Make sure your program can handle common input errors:
    • If the user tries to remove or edit an item that is not in the list, display an error message.
    • If the user enters an invalid menu option, display an error message and display the menu again.

Step 8: Make the Code More Readable with Functions

Grouping each action in a function makes the menu readable and lets you fix one operation without touching the rest of the program.

  1. Create functions for each action (for example: show_list(), add_item(), remove_item(), etc.).
  2. Change your program so that it uses these functions, which will make it more readable and organized.

Best practices for working with lists

A few habits avoid common mistakes with lists and make the code more readable. They cover comprehensions, copies, sorting and string assembly.

Prefer list comprehensions for simple operations

List comprehensions are not only more concise, but often faster than traditional loops to create or transform lists. For example, to get a list of squares:

squares = [x ** 2 for x in range(10)]

This syntax is clearer and more efficient than building a list with a for loop.

Avoid modifying a list while looping over it

Modifying a list while looping over it can cause unexpected behavior, especially when removing elements. If you need to transform a list, it is often better to create a new list rather than modify the original one:

# Bad practice
for element in my_list:
if element < 10:
my_list.remove(element)
# Good practice: use a list comprehension to filter
new_list = [element for element in my_list if element >= 10]

Use list copies to preserve the integrity of the original list

If you need to keep the original list intact while modifying it temporarily, create a copy with copy() or the slice [:]:

my_list = [1, 2, 3]
list_copy = my_list[:] # Or my_list.copy()
list_copy.append(4)
print(my_list) # Prints [1, 2, 3]
print(list_copy) # Prints [1, 2, 3, 4]

This practice is particularly important when you pass lists to functions, because Python passes lists by reference, which can lead to unexpected modifications of the original list.

Beware of nested lists and deep copies

If you work with nested lists, it is important to know that copy() or the slice [:] only create a shallow copy. This means the sublists are not copied independently. To create a deep copy of a nested list, use the copy module and its deepcopy() function:

import copy
nested_list = [[1, 2], [3, 4]]
deep_copy = copy.deepcopy(nested_list)
deep_copy[0][0] = 9
print(nested_list) # Prints [[1, 2], [3, 4]]
print(deep_copy) # Prints [[9, 2], [3, 4]]

The deep copy creates duplicates of all the sublists, thus preserving the original list.

Optimize costly operations

Sorting (sort()) and reversing (reverse()) modify the list in place. To get a sorted version without touching the original list, use the sorted() function. For a reversed version, reversed() returns an iterator, not a list: wrap it in list(), as in list(reversed(my_list)). Here is sorted():

my_list = [3, 1, 4, 2]
descending = sorted(my_list, reverse=True)
print(my_list) # Prints [3, 1, 4, 2]
print(descending) # Prints [4, 3, 2, 1]

sorted() directly returns a new list, and list(reversed(...)) does the same for the reverse order: the original list stays intact.

Limit conversions between lists and other data types

Python lets you convert lists to other types, such as tuples or sets, but each conversion uses resources. Limit unnecessary conversions and make sure the conversion is really needed to optimize the performance of your code:

my_list = [1, 2, 2, 3]
unique = set(my_list) # Conversion to remove duplicates
print(unique) # Prints {1, 2, 3}

In this example, the conversion is justified to remove duplicates, but an unnecessary conversion can slow the program down.

Use join() to assemble lists of strings

If you work with lists of strings that you need to assemble, join() is much more efficient than successive concatenations. For example:

words = ["Python", "is", "great"]
sentence = " ".join(words)
print(sentence) # Prints "Python is great"

These habits reduce the risk of mistakes: above all, remember not to modify a list while looping over it, and to copy before modifying a list that another part of the code uses.

Key takeaways

  • Creation with square brackets: [] for an empty list, [1, 2, 3] with values, list(range(10)) for a sequence.
  • Access by index starting at 0; -1 is the last element; the slice [1:4] extracts a sublist.
  • Add/remove: append, insert, extend; remove, pop, del.
  • Loop with for element in my_list; enumerate() gives the index and the value.
  • sort() sorts in place, sorted() returns a new sorted list without modifying the original.
  • List comprehension: [x**2 for x in my_list] replaces a loop with a concise expression.
  • Copy: [:] or copy() make a shallow copy; copy.deepcopy() for nested lists.

FAQ: frequently asked questions

The short answers below cover the most searched questions about Python lists. Each example is self-contained and tested on Python 3.12.