Python. Methods for working with lists. Examples

Methods for working with lists. Examples


Contents



1. How to call the method to work with the list? General form

The Python programming language provides a large set of methods for handling lists. These methods implement almost all the necessary conversions or operations on lists.

If a list with a certain name is specified, the processing method of this list is called using a common form.

ListName.MethodName(parameters)

here

  • ListName – the name of the list (of the “list” type);
  • MethodName – name of the method that is invoked;
  • parameters – list of parameters separated by comma ‘ , ‘. Some methods have no parameters.

The separator between the list name and the method name is the ‘ . ‘ (point).

 

2. Examples demonstrating the use of list class methods when working with lists
2.1. The append() method. Adding an item to the list

The append() method is used to add an item to the list. A method can receive only one parameter. The method parameter can be any object: number, string, list, etc.
An example of using the append() method

# method append() - adding items to the list
# specified list
A = [ 2, 3.78, 'abcde', True ]

# add 1 item to the list
A.append(7) # A = [2, 3.78, 'abcde', True, 7]
print("A = ", A)

# form a list of squares of numbers from 1 to 10
# using method append()
B = []
i = 1;
while i<=10:
    B.append(i*i)
    i=i+1

print("B = ", B)

The result of the program

A = [2, 3.78, 'abcde', True, 7]
B = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 

2.2. Method extend(). List extension

This method allows you to expand the list. The input parameter of the method is another list that is added to the data. An extension list can be a named object or a list in square brackets [ ].

An example of program that contains the extend() method

# Method extend() - list extension
# specified two lists
A = [ 2, 3.78, 'abcde', True ]
B = [ "Hello", 77, 1.84 ]

# expand list A by the value of list B
A.extend(B) # A = [2, 3.78, 'abcde', True, 'Hello', 77, 1.84]
print("A = ", A)

# form a list of squares of numbers from 1 to 10
# using method extend()
D = []
i = 1;
while i<=10:
    D.extend([i*i]) # add list [i*i] to list D
    i=i+1

print("D = ", D)

The result of the program

A = [2, 3.78, 'abcde', True, 'Hello', 77, 1.84]
D = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 

2.3. Method insert(). Insert an item into the list at a given position

The insert() method allows you to insert a new item into the list at a given position. The method takes two parameters. The first parameter – the insertion position, which starts at 0. The second parameter is the name of the object (value) that is inserted.
An example of using the insert() method

# method insert() - insert a single item in the list
# specified list
A = [ 1, 2, 3, 4, 5]

# insertion in position 2 of the new number 777
A.insert(2, 777)

print("A = ", A)

# form a list of squares of numbers from 1 to 10
# using the method insert()
D = []
i = 10;
while i>=1:
    D.insert(0, i*i)
    i=i-1

print("D = ", D)

The result of the program

A = [1, 2, 777, 3, 4, 5]
D = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

The insert() method allows you to insert a list into a list. For example, if the above program line

A.insert(2, 777)

replace with string

A.insert(2, [777])

then in this case, list A will be as follows

A = [1, 2, [777], 3, 4, 5]

that is, it is the usual use of nested lists.

 

2.4. The index() method. Determining the index of an item in the list

The index() method allows you to get the value of the index (position) of the specified list item. The method takes 1 parameter, which is the desired item. The index value that corresponds to the first item in the list is 0.
An example of using the index() method

# method index()
# specified list
A = [ 'a', 'b', 'c', 'd', 'e', 'f' ]

t = A.index('c') # t = 'c'

print("t = ", t)

The result of the program

t = 2

If the item is not in the list, an error message is displayed. For example, if in the above code the string

t = A.index('c')

replace with string

t = A.index('g') # t = 'c'

then the Python interpreter will give an error message

ValueError: 'g' is not in list

 

2.5. Method count(). Determining the number of occurrences of a given item in the list

The count() method returns the number of occurrences of the specified item in the list. The method takes one parameter.

# method count() - the number of occurrences of the specified item in the list
# specified list
A = [ 'a', 'b', 'c', 'd', 'e', 'f' ]

na = A.count('d') # na = 1

B = [ 1, 3, 5, 3, 2, 4 ]
nb = B.count(3) # nb = 2

print("na = ", na)
print("nb = ", nb)

The result of the program

na = 1
nb = 2

 

2.6. Method sort(). Sort the list

The sort() method is used to sort the list. By default, the method sorts the list items in ascending order of values. The method can change the sort order with the following named arguments:

  • key – an argument that allows you to define your own comparison function when calling the sort() method. This function takes one single argument and returns the value to be used in the comparison operation;
  • reverse is an argument used to specify the sort order of the elements. If reverse = True, the list items are sorted in descending order.

Example 1. Using sort() method to sort the list in ascending order.

# method sort() - sorting the list
# specified list
A = [ 'a', 'f', 'v', 'd', 'n', 'b' ]

# sorting
A.sort()

B = [ 1, 3, 5, 10, 2, 8 ]
B.sort()

print("A = ", A)
print("B = ", B)

Program execution gives the following result

A = ['a', 'b', 'd', 'f', 'n', 'v']
B = [1, 2, 3, 5, 8, 10]

In order to use the sort() method, all elements of the list must be either numeric or lowercase. For example, the following code

# error!
C = [ "Hello", "ABC", 7 ]
C.sort()

will generate an error

TypeError: '<' not supported between instances of 'int' and 'str'

Example 2. Sort the list in descending order. In order to sort the list in descending order, it is necessary that the value of the named reverse argument be True. The following example sorts the C list in descending order of elements.

# method sort() - sorting of list
# specified list
C = [ 2, 3, 1, 5 ]
C.sort(reverse = True) # sort in descending order
print("C = ", C)

The result of the program

C = [5, 3, 2, 1]

Example 3. Sort the list with the given key. The example sorts strings that are previously reduced to upper case: ‘aBc’ => ‘ABC’ with the upper() function

# method sort() - sorting the list with the given key
# specified list of strings
S = [ "aBC", "ABCD", "ab", "ABCC", "DEFf" ]

S2 = list(S) # create a new list
S2.sort(key=str.upper) # sort with key

S3 = list(S) # another list
S3.sort(key=str.upper, reverse=True) # sort with key and reverse arguments

print("S = ", S)
print("S2 = ", S2)
print("S3 = ", S3)

The result of the program

S = ['aBC', 'ABCD', 'ab', 'ABCC', 'DEFf']
S2 = ['ab', 'aBC', 'ABCC', 'ABCD', 'DEFf']
S3 = ['DEFf', 'ABCD', 'ABCC', 'aBC', 'ab']

 

2.7. Method reverse().Reversing of list

The reverse() method is used to reverse the order of the list items. An example of using the method

# method reverse()
# two lists are given
A = [ 1, 2, 3, 4, 5 ]
B = [ True, 7.78, 2.85, -1000, "bestprog.net" ]

# reversing of lists
A.reverse()
B.reverse()

print("A = ", A)
print("B = ", B)

The result of the program

A = [5, 4, 3, 2, 1]
B = ['bestprog.net', -1000, 2.85, 7.78, True]

 

2.8. The method pop(). Pop an item from the list

The pop() method is used to pull (delete) an item from the list. The method has two implementations that differ in the number of parameters obtained:

  • implementation without parameters. In this case, the last element of the list is pulled out;
  • implementation with one parameter. In this case, the parameter is the index of the element that needs to be pulled out from the list. Index 0 corresponds to the first item in the list.

An example of using the pop() method

# method pop()
# specified list
A = [ 5, 3.8, True, False, "ABCD" ]

# delete last item
A.pop() # A = [5, 3.8, True, False]

print("A = ", A)

# remove item with index 1
A.pop(1) # A = [5, True, False]

print("A = ", A)

The result of the program

A = [5, 3.8, True, False]
A = [5, True, False]

 

2.9. Method remove(). Remove a specified item from the list

The remove() method removes the specified item from the list. If there are several elements in the list with the specified value, the first occurrence of the specified element is deleted.
An example of using the remove() method

# method remove()
# specified list
A = [ 5, 3.8, True, 3.8, True, False, "ABCD" ]

# delete the first element that is true
A.remove(True)

# delete the first element, which is equal to 3.8
A.remove(3.8)

print("A = ", A)

The result of the program

A = [5, 3.8, True, False, 'ABCD']

 


Related topics