Python List Methods

python list methods
k

03/05/2024

Python List Methods

Python list methods are an important part of the Python programming language. In this article we will see several methods for Python lists. At the same time, we must understand that if we have a variable with a sequence of values that is what we call a list.

An example of a list could be car = [‘Audi’, ‘Mini’, Mercedes’]. The elements of the lists are separated by commas and in turn all of them are enclosed in [ ].

Append()

The append( ) method adds an item to the end of the list. The syntax is: list_name.append(new_element)

So there is a mutation of the initial list, that is to say that if before the append() method the list had 4 elements, then it will have 5.

Py

# let's suppose we have a list
numbers = [ 2,5,8,9,10 ]
# we add a new item -> 4
numbers.append(4)
# we print on the screen the list
print(numbers)
# [ 2,5,8,9,10,4 ]
# As you can see the new item 4 has been added to the end of the list

 

# Let´s do the same with the list cars
cars = [ 'Mini', 'Renault', 'BMW', 'Jaguar' ]
# we add a new item -> 'Dacia'
cars.append('Dacia')
# Let´s print the list on the screen
print(cars)
# [ 'Mini', 'Renault', 'BMW', 'Jaguar', 'Dacia' ]

Insert()

The insert( ) method adds an element to the list. With this method we will have to specify the index where we will "insert" the new element into the list. The syntax is: list_name.insert(index, new_element)

We also have a mutation of the initial list, so if the list had 5 elements after the insert it will have more elements.

Py

# Let´s suppose we have a list numbers
numbers = [ 2,5,8,9,10 ]
# We add a new item -> 4 at the index 2
numbers.insert(2,4)
# we print on the screen the list
print(numbers)
# [ 2,5,4,8,9,10 ]
# As you can see the new item 4 is in the index 2.

 

# Another example of insert with the list cars
cars
= [ 'Mini', 'Renault', 'BMW', 'Jaguar' ]
# now we add a new item -> 'Dacia' at the index 3
cars.append(3, 'Dacia')
# we print cars
print(cars)
# [ 'Mini', 'Renault', 'BMW', 'Dacia', 'Jaguar' ]

Extend()

The extend( ) method concatenates lists. It basically adds one list immediately after the other list. The syntax of this method is list_name.extend(other_list_name).

Again, there is a mutation after this method, as the initial list absorbs the one we have added to it. If we print on screen the initial list will reflect the sum of both and not how it was initially.

Py

# Let´s use two lists 
letters = ['a','b','c','d']
numbers = [2,4,6,8,10]
print(letters)
# ['a', 'b', 'c', 'd']
print(numbers)
# [2, 4, 6, 8, 10 ]

 

  # we add the list letters to numbers
 numbers.extend(letters)
 # we print both lists on the screen again
 print(letters)
 # ['a', 'b', 'c', 'd']
 print(numbers)
 # [2, 4, 6, 8, 10, 'a', 'b', 'c', 'd']

Sort()

The sort( ) method in Python lists performs a numerical or alphabetical sort of the list items. The syntax of this method is list_name.sort().

The type of mutation that occurs after the sort() method is positioning, i.e. the elements can acquire a new index within the list when sorted.

Also note that the sort() method can have a parameter - reverse - that can indicate the direction of the sort.

If the parameter reverse = True, then the elements are sorted from most to least. If reverse = False, they will be sorted from smallest to largest. The latter is the default parameter if not specified.

Py

# We use the list numbers for this example
numbers = [1,8,90,45,123,49,3 ]
print(numbers)
# [1, 8, 90, 45, 123, 49, 3]
# we print the item with index 4 in order to compare it later
print(numbers[4])
# 123
# we apply sort()
numbers.sort()
print(numbers)
# [1, 3, 8, 45, 49, 90, 123]
# we print the item with index 4 after we applied sort()
print(numbers[4])
# 49
# Initially index 4 was 123 and afterwards it was 49

Sorted()

The sorted( ) method in python lists returns a copy of the list but with the elements sorted if they are not sorted. The sorting of the items in the list is either numerical or alphabetical. The syntax of this method is sorted(list_name).

This type of method does not produce a mutation, since what it does is to sort the elements. If we were to print the initial list again, it would show us again the list without sorting.

Note that the sorted() method can also have a parameter - reverse - that can indicate the direction of the sorting.

If the parameter reverse = True, then the elements are sorted from most to least. If reverse = False, they will be sorted from smallest to largest. The latter is the default parameter if not specified.

Py

# Our list for this example is digits 
digits = [3, 89, 23, 1, 125, 50]
# we print digits
print(digits)
# [3, 89, 23, 1, 125, 50] -> list without being sorted# then we apply sorted() and print the result
print(sorted(digits))
# [1, 3, 23, 50, 89, 125] # we print the list digits again after sorted()
print(digits)
# [3, 89, 23, 1, 125, 50]

# To show alphabetical sorting we use the list cars
cars = ['Dacia','Renault','Mini','Audi','Seat','Fiat']
# print the list cars
print(cars)
# ['Dacia', 'Renault', 'Mini', 'Audi', 'Seat', 'Fiat'] -> list without sorting
# Let´s apply sorted() and print the result
print(sorted(cars))
# ['Audi', 'Dacia', 'Fiat', 'Mini', 'Renault', 'Seat']
# list sorted alphabetically
# we print again the list cars
print(cars)
# ['Dacia', 'Renault', 'Mini', 'Audi', 'Seat', 'Fiat']
# it returns the original list

Pop()

The pop( ) method in python lists is used when we want to remove or delete an item from the list. In this method we have to specify the index of the element we want to remove, otherwise it will remove the last element.

The syntax of this method is list_name.pop(index_element_to_remove).

Once we have removed an item from the list, it does not return, unless we use a python method to add it back. The list will have one less element than it had before. This python method will return the deleted item.

Py

# We use the cars list for this example
cars = ['Dacia','Renault','Mini','Audi','Mazda']
# we print cars on screen
print(cars)
# ['Dacia', 'Renault', 'Mini', 'Audi', 'Mazda']
# We delete the item with index 1 -> Renault
cars.pop(1)
# Let´s print the cars list again after pop()
print(cars)
# ['Dacia', 'Mini', 'Audi', 'Mazda']

  # Now we delete the last item on the list as we do not specify the index
 cars.pop()
 print(cars)
 # ['Dacia', 'Mini', 'Audi']
 # As you see we deleted 'Mazda'

del[ ]

The del[ ] method deletes an element from the list. Between the [ ] we have to put the index of the element we want to delete. The syntax of this method is del list_name[index_element_to_delete].

With this python method we can delete more than one element at a time using slicing. Del is a python method that does not return the deleted item, only the list without that item.

If instead of specifying a single index, for example of cars[3], we specify a beginning and end section, for example of cars[:3]. In the first case we delete the element from index 3, and in the second case we delete the elements between index 0 and 3 - index 3 is not included in the deletion.

Py

# We use the list numbers as example
numbers = [5,10,15,20,30,55,890]
# Let´s suppose we want to delete the item with index 3 -> 20
del numbers[3]
# let´s print the list numbers after we applied del
print(numbers)
# [5, 10, 15, 30, 55, 890]
# the item 20 has been deleted

 # Now we delete several items at the same time with index 3 to 5 - > 30 and 55
 del numbers[3:5]
 # print the list numbers again after del
 print(numbers)
 # [5, 10, 15, 890]
 # From the initial list the items 30 and 55 have been deleted

Remove()

Another Python list methods is remove( ) which we use when we know the element we want to remove. That element is the parameter that this method needs. The syntax of this method is list_name.remove(element_to_remove).

If we introduce as parameter a value that is not part of the list we will get an error message ValueError:list.remove(x): x not in the list

Py

# Let´s use the list cars
cars = ['Dacia', 'Renault', 'Audi', 'Hyundai', 'Mercedes']
# We apply remove() to the item 'Hyundai'
cars.remove('Hyundai')
# let´s print the list cars
print(cars)
# ['Dacia', 'Renault', 'Audi', 'Mercedes']
# You can see that 'Hyundai' has been removed from the list

Knowing Python list methods is essential to be able to program in Python when they take their first steps in programming. If you want to continue learning how to programm in Python, you can find more resources in this link.

Creatuwebpymes, is a web design and web positioning company in the Canary Islands that ❤️ programming.

 

creatuwebpymes quien somos

Francisco Brito Diaz

CEO of creatuwebpymes.com, web design and digital marketing company in the Canary Islands