Register to get access to free programming courses with interactive exercises

Modifying lists by elements Python: Lists

As you'll remember, list elements are indexed, meaning they have sequence numbers. The first element has an index of 0, and the last one has len(list) - 1 index.

The function len() returns the length of a list, but it works with different types, such as strings and tuples.

List items can be obtained and replaced by assigning them to their index. If we specify a negative index, we take elements from the end.

The last element of the list will have a negative index, -1. Sadly, there's no way to use -0. Here are a couple of examples of using indexes with a list:

l = [0] * 3
l[0], l[1] = 10, 32
l[-1] = l[0] + l[1]
print(l)  # => [10, 32, 42]

Note that we created the list by cloning zeros. It's safe to do so because Python numbers are immutable. However, we do all list modifications through assignment, so we wouldn't get anything unexpected even if we used mutable objects.

The pop and insert methods

So, we know how to get and replace elements one by one. It would also be nice to be able to delete old items and insert new ones in the middle of the list. The pop and insert methods are responsible for this.

The pop removes an element by index. If we don't specify an index, Python will delete the last element. In doing so, the pop returns the deleted value:

l = [1, 2, 3]
l.pop()  # 3
print(l)  # => [1, 2]
l.pop(0)  # 1
print(l)  # => [2]

And here's an example of the insert being used:

l = [1, 2, 3]
l.insert(1, 100)
print(l)  # => [1, 100, 2, 3]
l.insert(-1, 200)
print(l)  # => [1, 100, 2, 200, 3]

The insert method always inserts a new item before the item with the specified index relative to the beginning of the list. It doesn't matter whether we counted the index from the beginning or the end. And insert(-1, ..) inserts an element before the last one.

Interestingly, l.insert(len(l), x) will add element x to the end of list l. In other words, it will work like l.append(x).

There will be no element before which we can insert the new one. So, it will go to the end of the list. Keep this feature in mind, but it's better to use append if only because its call is easier to read.

Indexing errors

If you try to call pop() on an empty list or specify an index beyond the indexes of existing items, you'll get IndexError:

l = []
l.pop()
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# IndexError: pop from empty list

But insert is more tolerant of invalid indexes and adds elements from the appropriate end:

l = [0]
l.insert(-500, 1)
l.insert(1000, 2)
print(l)  # => [1, 0, 2]

However, we should not rely on it. It is better to keep indexes under control.

Sorting and unfolding

Lists of things occasionally have to be sorted and sometimes unfolded. It's best to be able to do it effectively. Therefore, lists already have built-in tools to perform both tasks, the sort and reverse methods. Both methods modify the list in place. Let's look at some examples:

l = [1, 3, 7, 2, 10, 8]
l.sort()
print(l)  # => [1, 2, 3, 7, 8, 10]
l.reverse()
print(l)  # => [10, 8, 7, 3, 2, 1]

These methods can work without parameters. In the case of reverse. We do not need any parameters because unfolding is the same any day of the week.

But Python can sort according to different criteria. If you call sort without parameters, the items will be in ascending order. However, you can pass a parameter function to the method. It will return the sorting criterion — the key.

The function will be called once for each item in the list, after which the items will be in ascending order of the key value. Let us declare a function that returns the remainder of an argument divided by two, and we'll use it as a key:

def mod2(x):
    return x % 2

l = [1, 2, 3, 6, 5, 4]
l.sort(key=mod2)
print(l)  # => [2, 6, 4, 1, 3, 5]

We have passed the function in the sort method with the parameter name. We'll look at this syntax later, but you can already experiment with the sort method and the different key functions by specifying them by analogy.

The mod2 function returned 0 and 1 for even and odd numbers, respectively. Therefore, even numbers ended up at the beginning of the list first.

Note that the numbers retained their order within their group: 6 went before 4 in the list, and we preserved this mutual arrangement.

One of the essential features of a sorting algorithm is its capability to preserve the relative order of the items we have already sorted. It's called stability. The sorting is always stable in Python.

The key function doesn't have to return numbers. It can output any value that Python knows how to compare.

Let's complicate the key function from the previous example:

def key(x):
    return (x % 2, x)

l = [1, 2, 3, 6, 5, 4]
l.sort(key=key)
print(l)  # => [2, 4, 6, 1, 3, 5]

Now the numbers are divided into groups and sorted within the groups. Working with tuples, Python compares the first elements first. When they're equal, it goes to the second ones, and so on.

The values are compared until we find the first inequality or until one of the tuples runs out, in which case the shorter one will be smaller. There are a few examples:

print((1, 2, 3) < (1, 2, 4))  # => True
print((1, 1) < (1, 1, 1))  # => True
print((1, 2) > (1, 1, 1))  # => True
print((3, 4, 5) == (3, 4, 5))  # => True

In this lesson, we have discussed the general principles of working with lists but have not covered the count, remove, or index methods. It is up to you to learn about them.


Recommended materials

  1. Stable sorting

Are there any more questions? Ask them in the Discussion section.

The Hexlet support team or other students will answer you.

For full access to the course you need a professional subscription.

A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY
Suggested learning programs
profession
new
Developing web applications with Django
10 months
from scratch
under development
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.