Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Lists: Mutable & Dynamic

In this lesson, you’ll explore how Python lists are both mutable and dynamic. Many types in Python are immutable. Integers, floats, strings, and (as you’ll learn later in this course) tuples are all immutable. Once one of these objects is created, it can’t be modified, unless you reassign the object to a new value.

The list is a data type that is mutable. Once a list has been created:

  • Elements can be modified.
  • Individual values can be replaced.
  • The order of elements can be changed.

Lists are also dynamic. Elements can be added and deleted from a list, allowing it to grow or shrink:

>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']

>>> a[2]
>>> a[2] = 10
>>> a
['spam', 'egg', 10, 'tomato', 'ham', 'lobster']
>>> a[-1] = 20
>>> a
['spam', 'egg', 10, 'tomato', 'ham', 20]

>>> s = 'mybacon'
>>> s[2]
>>> s[2] = 'f'
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    s[2] = 'f'
TypeError: 'str' object does not support item assignment

>>> a
['spam', 'egg', 10, 'tomato', 'ham', 20]
>>> del a[3]
>>> a
['spam', 'egg', 10, 'ham', 20]
>>> len(a)
>>> a[2:5] = [1.1, 2.2, 3.3]
>>> a
['spam', 'egg', 1.1, 2.2, 3.3]
>>> a[1:4]
>>> a[1:4] = ['Hello']
>>> a
['spam', 'Hello', 3.3]
>>> a[1:2] = ['a', 'b', 'c', 'd']
>>> a
['spam', 'a', 'b', 'c', 'd', 3.3]
>>> len(a)
>>> a[1]
>>> a[1] = [22, 33, 44]
>>> a
['spam', [22, 33, 44], 'b', 'c', 'd', 3.3]
>>> del a[1]
>>> a
['spam', 'b', 'c', 'd', 3.3]
>>> a[1:1] = [22, 33, 44]
>>> a
['spam', 22, 33, 44, 'b', 'c', 'd', 3.3]
>>> a[1:5]
[22, 33, 44, 'b']
>>> a[1:4] = []
>>> a
['spam', 'b', 'c', 'd', 3.3]

>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a += ['gravy', 'kiwi']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster', 'gravy', 'kiwi']
>>> a = [10, 20] + a
>>> a
[10, 20 'spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster', 'gravy', 'kiwi']

>>> a += 30
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    a += 30
TypeError: 'int' object is not iterable

>>> a += [30]
>>> a
[10, 20 'spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster', 'gravy', 'kiwi', 30]
>>> type([30])
<class 'list'>
>>> type(30)
<class 'int'>

>>> a = ['spam', 'egg', 'bacon']
>>> a
['spam', 'egg', 'bacon']
>>> a += 'tomato'
>>> a
['spam', 'egg', 'bacon', 't', 'o', 'm', 'a',' t', 'o']
>>> a[3:] = []
>>> a
['spam', 'egg', 'bacon']
>>> a += ['tomato']
>>> a
['spam', 'egg', 'bacon', 'tomato']

00:00 For this video, I’m going to show you how lists are mutable and dynamic. So many of Python object types are immutable. Things like an integer or a float, or even a sequence type object like a string—they’re all immutable, meaning that you can’t change the characters within that string or change the value of that integer or that float.

00:20 Once you create that object and you assign it, it’s immutable unless you reassign it. And we’re going to discuss another cousin of a list called the tuple and how it’s immutable also. So, lists are pretty unique. They are mutable.

00:33 Once you create it, elements can be modified, individual values can be replaced, even the order of the elements can be changed. And lists are also dynamic, meaning that you can add elements to the list or remove elements from a list completely. So the list can grow or shrink depending on how you use it.

00:55 Let me have you try it out. A single value in a list can be replaced by indexing and then doing simple assignment. Say you had list

01:07 and then you were to index a particular item—such as in this case, a[2], which is 'bacon'—but instead of just calling it out to have it returned, reassign it. Put an integer, 10.

01:21 That’s changed it, changed the value within the list. Do another one. Take the last one, change that to an integer of 20. If you’ve worked with strings before, you might remember that

01:37 if you try to reassign this, the third index, the letter 'b' in the string, that’ll raise an exception, a TypeError. It tells you straight up that the 'str' object does not support item assignment, the way a list does.

01:52 Not only can you change out that item from your list, but you can use the del (delete) function. And let’s say you delete a[3].

02:05 Well, that deleted 'tomato' right out of that list. If you wanted to change several contiguous elements in a list all at one time, instead of just index assignment, you could do it with slice assignment. Here you’ll put in m being your first index, and n being again going up to but not including.

02:25 And then in here you just put an iterable, such as a list. That’s what it would look like. So let’s say we want to change these three.

02:37 So a has a length of 5 now.

02:42 And then you could just enter a list. Let’s put some floats in.

02:50 And you can see it’s reassigned all three of those.

02:55 And it will replace a slice, let’s say 1 through 4, which should be these three items here. Let’s say you replaced it with just a single one. Again, a[1:4] should be those three. So in that case, it’s going to take all three of these items and replace it with a single list item. And if you want to insert multiple items, you can accomplish that too.

03:18 Let’s say between 1 and 2—basically meaning this item right here, 'Hello'—you wanted it to be…

03:32 So now you’ve inserted four of these items in the place where it was this one, so the length now of a is actually 6.

03:41 Now, this is what we’re talking about the list being dynamic. Python just grows or shrinks the list as needed. Now, one note: if you aren’t using a slice syntax here, and let’s say you just say a[1], which is 'a' here, if you were to replace a[1] and not a slice with a list, it’s going to insert that as a sublist, because it’s not indicating a slice here. So if you wanted to insert all three of these items differently—so let’s say, again, you might remember del—and you wanted right in here to insert these three items, well, that would be a[1:1]

04:23 and that would insert all three of these before the rest. Basically a zero-length slice as the index. And if you want to delete multiple items, another way that you could accomplish that—let’s say you want to get rid of all the integers in here. Well, you would say from a[1:5]. So again, here, a[1:4], and then you’d reassign it to an empty list. That would remove those, deleting them. So what about appending items to a list? Well, we were using the concatenation operator earlier.

05:00 Rebuild a as a list of those strings again. So here’s a. A version of the concatenation operator that’s also called the augmented assignment operator would allow you to append a couple additional items onto your list,

05:18 putting them at the tail of the list here. What if you wanted some at the beginning? Well, you could do it a little differently. If you assign to a a list, let’s say with a couple of integers at the beginning, and then concatenated it to a itself, that would put the two at the beginning, prepending as opposed to appending to the list a. And so you might say, “Can I just add on a single item?” If you were to += and then just add a 30 as an integer to the end of it, it’s going to be mad because it’s not an iterable.

05:53 So you can’t just add a simple integer to it. It has to be an iterable. So that’s where you could use that singleton list. In this case, += [30]it doesn’t have a problem with that because type([30]) is a list, compared to type(30) without square brackets is an integer. Okay, if you’ve worked with strings, you might be aware that a string is an iterable. Okay, what happens if you add it? Let me simplify a a little bit, make it a little bit shorter. That’s good. So here’s a, and let’s say you wanted to add 'tomato' to your list.

06:29 What do you think is going to happen? Well, it might not be the way you thought. In this case, since this is an iterable, it broke it apart into individual characters. You could practice it a little bit here.

06:38 So, this is 3 and we could go up to the end and say that’s equal to an empty list. That should clear those out, right? Okay, perfect. If you wanted to add it more properly, 'tomato' would have to be inside of a list as a singleton. Next, you get to practice the methods that are available to lists.

strings are immutable. so the code below does not work. s = ‘mybacon’ s[2] = ‘f’

what about code below? what are the differences? Thanks. s = ‘abc’ s = ‘abcdef’

Avatar image for Chris Bailey

Chris Bailey RP Team on Dec. 11, 2019

Hi DJ, In your first code example you are trying to mutate the string that is assigned to s, by accessing the third element (item) and changing it. Which will throw: TypeError: ‘str’ object does not support item assignment.

In your second code example you are reassigning the object s to a new value, which is possible. You aren’t changing the “string” but instead giving s a wholly different string. As python is a dynamically typed language you could even reassign s to an integer, or a some other type than a string. (s = 42) or s = [1, 2, 3].

Make sense. BTW: The tutorial is very help. Thank you, Chris.

Avatar image for Minh Pham

Minh Pham on March 22, 2020

Hi Chris,

I like the way you teach this Python course and I am looking for similar course formats as offrened in RealPython, in other language as C# Java SQL, with the following criteria:

  • Iteractive
  • Video lecture & and Code in text
  • Quiz
  • Excercise
  • Small project

Can you recommend me some

Regards Minh

Avatar image for birajksahu

birajksahu on June 14, 2020

Hi Chris, Might sound trivial but I am not able to get the link about sort in description of the video. I am not sure where to locate the description of a video. BTW, loving the list and tuple video series :)

Avatar image for birajksahu

birajksahu on June 14, 2020

Please ignore got the answer myself :)

Avatar image for techsukenik

techsukenik on Sept. 14, 2021

This section was very useful for me. I did not realize the full power of slice. Thanks for the info.

Can you include in this section how to insert values in the middle of the list?

For example: Code:

num_list = list(range(10))
print("Before insert",num_list)
num_list[5:6] = [num_list[5],'insert-1','insert-2']
print("After insert",num_list)


Before insert [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
After insert [0, 1, 2, 3, 4, 5, 'insert-1', 'insert-2', 6, 7, 8, 9]
Avatar image for useeme2ndtime

useeme2ndtime on Nov. 3, 2021

@techsukenik I tried achieve it using this piece of code which I made:

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

print(f"My list before change is \n{a}")
print(f"Lenght of my list is {len(a)}")

# Check the middle index of list by dividing whole list length by 2
b = len(a) / 2

# Change middle index number from float to int
b = int(b)
print(f"Middle index of my list is {b}")

# Add values into middle of list
a[b:b] = ["insert-1", "insert-2"]

print(f"My list after modification is \n {a}")

Output is:

My list before change is 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Lenght of my list is 10
Middle index of my list is 5
My list after modification is 
 [0, 1, 2, 3, 4, 'insert-1', 'insert-2', 5, 6, 7, 8, 9]

Become a Member to join the conversation.