Modify lists

Changing the value of a list element in Python is easy:

my_numbers[0] = 6
print(my_numbers[0])

The output confirms that the first item of the list has been modified:

>>>
6
>>>

We can add more items to the end of the list in one of two ways:

• by adding another list to the current list and storing the result as another list:

my_numbers = [5,3,2,7]
my_numbers_new = my_numbers + [100,55]

print(my_numbers_new)
>>>
[5, 3, 2, 7, 100, 55]
>>>

• by using the append() function:

my_numbers = [5,3,2,7]
my_numbers.append(999)

print(my_numbers)
>>>
[5, 3, 2, 7, 999]
>>>
The append() function can take only a single argument, so if you need to add multiple items to a list, you will need to use the append() function multiple times.

 

If you know the location of the item you would like to delete from a list, you can use the del statement to do so:

my_numbers = [5,3,2,7]
del my_numbers[1]
print(my_numbers)

>>>
[5, 2, 7]
>>>

In the output above you can see that we’ve removed the item at the index location of 1.

Here is way in which we can remove multiple items from the list:

my_numbers = [5,3,2,7]
my_numbers[:3] = []

print(my_numbers)

>>>
[7]
>>>

As you can see from the output above, the first three items in the list have been removed.

Geek University 2022