Python

Python

Python - Changing List Elements

Lists in Python are mutable, meaning we can change their contents after they are created. In this section, we’ll dive deep into how to modify list elements: replacing values, working with indexes and ranges, and using methods to reorder elements. We won’t cover adding, removing, or looping through lists, as those topics are addressed separately.

Basics of Modifying List Elements

A list in Python is an ordered collection of items enclosed in square brackets []. Each element in a list has an index, starting at 0 for the first element. To modify an element, you simply access it by its index and assign a new value.

Changing a Single Element

The simplest way to modify a list element is to use its index and the assignment operator =.

📌 Example:

Here, we replaced the element at index 1 (the second element, since indexing starts at 0) from "banana" to "orange". The list changed, but its length stayed the same.

If you specify an index that doesn’t exist in the list, Python will raise an IndexError. For example:

Changing Multiple Elements at Once (Slicing)

Using a slice, you can replace multiple elements of a list at once. A slice is defined as [start:end], where start is the index of the first element and end is the index up to (but not including) which the replacement will occur.

📌 Example:

Note that the difference end - start gives the length of the slice or the number of elements being replaced.

In this example, we replaced the elements at indexes 1, 2, and 3 (range [1:4]) with the new values [20, 30, 40]. If the number of new elements matches the number of replaced ones, the list length remains unchanged.

If the number of replacement elements differs, Python adjusts the list length automatically.

📌 Example:

The elements [2, 3, 4] were replaced with a single value 99, and the list length decreased from 5 to 3.

Using Negative Indexes

In Python, you can access list elements from the end using negative indexes. For example, -1 is the last element, -2 is the second-to-last, and so on.

📌 Example:

We replaced the last element "green" with "yellow" using the index -1.

Negative indexes also work with slices:

📌 Example:

The slice [-3:-1] covers the elements at indexes -3 ("blue") and -2 ("green"), but excludes -1 ("yellow"). These two elements are replaced with "purple" and "orange".

Modifying Elements with a Step

Slices in Python support a third parameter—step—written as [start:end:step]. This allows you to modify elements at regular intervals.

📌 Example:

The slice [::2] means "take all elements from start to end with a step of 2" (i.e., indexes 0, 2, 4). These elements 10, 30, 50 are replaced with [100, 300, 500]. The number of new elements must match the number of elements being replaced (in this case, 3).

If the numbers don’t match, Python raises a ValueError.

Using Methods to Reorder Elements

Python provides methods to change the order of elements in a list without replacing their values, just by rearranging them.

The reverse() Method

The reverse() method reverses the list, flipping the order of its elements.

📌 Example:

The elements swapped positions: the first became the last, the second became the second-to-last, and so on. The values stayed the same; only the order changed.

The sort() Method

The sort() method sorts the list elements in ascending order (or descending if you specify reverse=True).

📌 Example:

The elements are rearranged in ascending order. The method modifies the original list in place.

For more details, see the section dedicated to sorting lists.

Modifying Elements with Calculations

You can combine index access with operations to modify elements based on their current values.

📌 Example:

We took the value at index 1 (200), multiplied it by 2, and assigned the result back to the same element.

A shorthand for this operation is: prices[1] *= 2

This can also be done for a range:

📌 Example:

The elements at indexes 1 and 2 (200 and 300) were increased by 50 and replaced with 250 and 350.

There’s no shorthand for this operation with slices. Attempting to use += with a slice will simply insert the new elements into the list:

And trying to use *= with a slice will raise a TypeError: can't multiply sequence by non-int of type 'list'.

Helpful Tips

  1. Check Index Bounds. Before modifying an element, ensure the index is within the list’s length to avoid an IndexError.
  2. Lists Are Mutable. Any modification affects the original list, not creating a new one (unlike strings, which are immutable).
  3. Experiment with Slices. Slices are a powerful tool for flexibly modifying multiple elements at once.

Advanced Techniques: Default Values

Python lists don’t have a built-in method like the dictionary get() method, which lets you specify a default value for non-existent indexes. However, there are several ways to achieve similar behavior when modifying or accessing list elements.

Method 1: Using try-except

You can wrap an attempt to modify an element in a try-except block to handle cases where the index is out of range, setting a default value as needed.

If the index (5) exceeds the list length (3), we append elements with the default value (0) until the list is long enough, then assign the new value.

Method 2: Checking List Length

Before modifying an element, you can check if the index exists and extend the list using extend() or append() if necessary.

If the index is greater than or equal to the list length, we use extend() to add default-value elements, then replace the target element with the new value.

Conclusion: The simplest and most "Pythonic" approach for most cases is either try-except or length checking, depending on whether you want to extend the list or ignore out-of-range indexes.

Method 3: Creating a Custom Class

You can create a wrapper around a list by defining a class to mimic behavior with a default value.

Here, we created a DefaultList class that automatically fills the list with default values (0) if an index beyond the current length is accessed.

Conclusion

Now you know how to replace individual elements by index, work with ranges using slices, reorder elements with methods like reverse() and sort(), and combine modifications with calculations. Mastering these techniques will let you confidently manipulate lists in your programs. Practice, experiment, and don’t fear mistakes—it’s the best way to learn!

Frequently Asked Questions About Modifying List Elements

How do I swap two elements in a list?

Method 1: Using a Temporary Variable

We use a temporary variable to hold one element while swapping the other.

This is a classic, easy-to-read approach.

Method 2: Multiple Assignment (Python-Style)

Python offers a more elegant way to swap elements using multiple assignment in a single line.

In Python, a, b = b, a swaps values automatically without a temporary variable. This works because Python evaluates the right side first, then assigns the values simultaneously.

How do I modify elements with a specific step?

Use a slice with a step. For example:

What happens if I use an index that doesn’t exist?

Python will raise an IndexError.

Can I replace multiple list elements at once?

Yes, use a slice. For example:

Subscribe to our newsletter

Get the freshest news and resources for developers, designers and digital creators in your inbox each week

© 2000 – 2025 SitePoint Pty. Ltd.
This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.