Summary of built-in methods in Python list

Before

--This article is a partial excerpt from a particular chapter of the book "Getting Started with Python Programming" (https://github.com/simon-ritchie/python-novice-book-preview). ――Because it is an introductory book, it is for beginners. --Mainly the contents of chapters related to built-in list operations and methods. --Please note that there are some parts that do not match the Qiita article (words such as "chapter" and "page" are used, the number of line breaks is extra, links do not correspond, etc.). If you are interested, please use the e-book version linked above (you can download it on Github). ――If you give us feedback in comments, we may use and reflect it on the book side as well.

Find out if it's in a list or dictionary: in

If you write the code in the format arbitrary value in target list, you can get the boolean value of whether the value is included in the list.

For example, the following code gets the boolean value of whether the value 200 is included in the list (True is returned because it is included).

list_value = [100, 200, 300]
is_in = 200 in list_value
print(is_in)

Output contents of code execution result:

True

If you specify a value (500) that is not included in the list, as in the code below, False will be returned.

list_value = [100, 200, 300]
is_in = 500 in list_value
print(is_in)

Output contents of code execution result:

False

Append value to the end of the list: append method

Use the append method to add a specific value to the end of the list. Specify the element you want to add to the first argument.

Instead of returning a copy of the list with the element added as the return value, the list itself that executed the method is updated (note that the description for the return value is not set).

This is because if you make a copy of the list every time you add an element, the processing load will increase if the list is large, so you do not make a copy like this.

list_value = ['Cat', 'dog']
list_value.append('rabbit')
print(list_value)

Output contents of code execution result:

['Cat', 'dog', 'rabbit']

Add element at a specific position: insert method

The append method appends the element to the end of the list, but the insert method allows you to append the element anywhere in the list.

In the first argument, specify the index of the position to be added, and in the second argument, specify the element you want to add.

The index starts from 0, so if you want to add an element at the beginning (first), specify 0 as the first argument.

Sample to add the word rabbit to the list at the beginning (index 0):

list_value = ['Cat', 'dog']
list_value.insert(0, 'rabbit')
print(list_value)

Output contents of code execution result:

['rabbit', 'Cat', 'dog']

Sample to add the word rabbit to the list second (index 1):

list_value = ['Cat', 'dog']
list_value.insert(1, 'rabbit')
print(list_value)

Output contents of code execution result:

['Cat', 'rabbit', 'dog']

If you try to add an element beyond the range of the list, it will be added at the end. For example, if you try to add an element to the 4th (index 3) or 5th (index 4) position for a list with only 2 items, the element does not exist at the 3rd position, so the 3rd position The addition is performed to (index 2).

list_value = ['Cat', 'dog']
list_value.insert(3, 'rabbit')
print(list_value)

Output contents of code execution result:

['Cat', 'dog', 'rabbit']

Add the contents of another list to a list: extend method

Use the extend method when you want to combine two lists into one. extend is a word that means "extend". Is it something like adding the value of another list to one list to expand (larger) it?

Execute the method with the list you want to add, and specify the list containing the values you want to add as the first argument.

The added value will be added after the value in the list to which it is added.

left_list = ['Cat', 'dog']
right_list = ['wolf', 'rabbit']

left_list.extend(right_list)
print(left_list)

Output contents of code execution result:

['Cat', 'dog', 'wolf', 'rabbit']

Tuples other than lists can be specified as arguments without any problem.

left_list = ['Cat', 'dog']
right_tuple = ('wolf', 'rabbit')

left_list.extend(right_tuple)
print(left_list)

Output contents of code execution result:

['Cat', 'dog', 'wolf', 'rabbit']

Extract elements from list: pop method

The pop method retrieves the value at a particular index position in the list. Pop has the meaning of "pop out" and is an image of a specific element in the list popping out.

The return value of the method is the value of the target element, and that value disappears from the list after execution.

In the first argument, specify the index position of the target element. Specifying 0 for the index retrieves the first element, and specifying 1 for the index retrieves the second element.

In the sample below, the second (index 1) value of'dog'is taken out from the list that stores the three values of the letters'cat',' dog', and'rabbit'.

Notice that the retrieved value is'dog'and that the subsequent list does not include the'dog' value.

list_value = ['Cat', 'dog', 'rabbit']
popped_value = list_value.pop(1)
print('popped_value:', popped_value)
print('list_value:', list_value)

Output contents of code execution result:

popped_value:dog
list_value: ['Cat', 'rabbit']

Remove the target element from the list: remove method

The remove method removes the element with a specific value in the list. As with pop, the contents of the list will be reduced, but unlike pop, it will be deleted by specifying a value instead of an index. For example, if you want to remove the value'dog'from the list, specify'dog'as the first argument.

list_value = ['Cat', 'dog', 'rabbit']
list_value.remove('dog')
print(list_value)

Output contents of code execution result:

['Cat', 'rabbit']

If the value of the argument specified to be deleted is included in the list, the first value is deleted.

In the sample below, the remove method is executed with the value'dog'in the list. You can see that the second value,'dog', remains in the list of results.

list_value = ['Cat', 'dog', 'rabbit', 'dog']
list_value.remove('dog')
print(list_value)

Output contents of code execution result:

['Cat', 'rabbit', 'dog']

Use the del keyword to remove an element in the list

You can remove a specific element in the list with the remove or pop methods, but you can also remove it with the del target list [index to be removed].

For example, if you want to delete the second value (index 1) of a variable in the list list_value, writedel list_value [1].

This method is suitable when it is not necessary to retrieve the value like pop (the retrieved value is not used afterwards) and you want to specify the index instead of the value and delete it.

list_value = ['Cat', 'dog', 'rabbit']
del list_value[1]
print(list_value)

Output contents of code execution result:

['Cat', 'rabbit']

Empty list: clear method

You can empty the list with the clear method.

If you try executing the clear method on the list that stores the three values as shown below, you can see that the contents of the list are empty ([]).

list_value = ['Cat', 'dog', 'rabbit']
list_value.clear()
print(list_value)

Output contents of code execution result:

[]

If you just want to make a variable an empty list, you can do it just by setting a new empty list to a variable as shown below.

list_value = ['Cat', 'dog', 'rabbit']
list_value = []
print(list_value)

Output contents of code execution result:

[]

So which one should I use? In that respect, the details are different when compared strictly, but it does not matter which one you use at first.

I'll mention the difference below, but it doesn't matter if you skip this explanation at first or read it and put it in the corner of your head.

For the sake of explanation, compare a container called a list to a cardboard container.

The clear method behaves like making an empty cardboard by removing all the contents while using the same cardboard.

On the other hand, the correspondence of setting an empty list as a variable is a control like preparing another empty cardboard (that is, two cardboards are used).

The code also makes a difference in some cases. We have prepared two functions that accept lists as arguments (clear_list and assign_blank_list) as shown below, and reflect the clear and empty lists in the variables of the functions, respectively.

As mentioned above, the clear method (clear_list function) uses the same cardboard to empty the contents, so the list (list_value_1) is empty after the function is executed.

On the other hand, if you set another empty list as a variable in the function (assign_blank_list), a second cardboard is assigned as a local variable in the function. Therefore, the variables outside the function (list_value_2 as the first cardboard) and the variables in the list inside the function (list_value as the second cardboard) are ** different values **.

The output content after executing the function of list_value_2 is also not empty, and the original value is retained.

def clear_list(list_value):
    list_value.clear()


def assign_blank_list(list_value):
    list_value = []


list_value_1 = ['Cat', 'dog', 'rabbit']
clear_list(list_value=list_value_1)
print('list_value_1:', list_value_1)

list_value_2 = ['Cat', 'dog', 'rabbit']
assign_blank_list(list_value=list_value_2)
print('list_value_2:', list_value_2)

Output contents of code execution result:

list_value_1: []
list_value_2: ['Cat', 'dog', 'rabbit']

Strictly speaking like this, the behavior is slightly different for each. However, in most cases, there is no problem with either performance, including performance, so you do not have to be aware of that at first.

Copy list: copy method

Use the copy method to copy the entire list. Calling this method sets a new list of return values.

In the code below, you can see that the same content as the copy source list is output in the copied list.

list_value = ['Cat', 'dog']
copied_list_value = list_value.copy()
print(copied_list_value)

Output contents of code execution result:

['Cat', 'dog']

If you just want to set the contents of the same list in another variable, you can do it just by specifying the equal symbol as shown below (the output result will be the same as before).

list_value = ['Cat', 'dog']
copied_list_value = list_value
print(copied_list_value)

Output contents of code execution result:

['Cat', 'dog']

However, although it is similar to the one described in the clear method section, it also behaves differently.

If you compare the container of the list with a cardboard box as in the case of the clear method, the copy method behaves like copying the cardboard together with the contents of the cardboard.

On the other hand, when setting the list value to another variable using the equal symbol, it is said that only one cardboard is used and the same one is used ** differently called ** (multiple variable names are given). It becomes a behavior.

This behavior makes a noticeable difference compared to the clear method (you usually need to be aware of it when writing code).

Let's check the difference in the code.

The first is the one that uses the copy method. Since this is a process of copying the entire contents of the cardboard box, even if the contents of the list after copying are updated, the contents of the list before copying will not change because the box itself is different. Only the copied list will be updated.

list_value = ['Cat', 'dog']
copied_list_value = list_value.copy()
copied_list_value[0] = 'rabbit'

print('Original list:', list_value)
print('List after copying:', copied_list_value)

Output contents of code execution result:

Original list: ['Cat', 'dog']
List after copying: ['rabbit', 'dog']

On the other hand, if you use the equal symbol and omit the description of the copy method and allocate a list of different variable names, the same box is referenced only by the difference in the name (name), so after copying If you update the value of the variable in the list of, the value of the list before copying will be changed at the same time.

list_value = ['Cat', 'dog']
copied_list_value = list_value
copied_list_value[0] = 'rabbit'

print('Original list:', list_value)
print('List after copying:', copied_list_value)

Output contents of code execution result:

Original list: ['rabbit', 'dog']
List after copying: ['rabbit', 'dog']

Each of these copying methods is called shallow copy and deep copy, respectively.

Shallow copy corresponds to the one that changes only the name (case that does not go through the copy method). Shallow does not copy the contents of the box, as it means "shallow".

On the other hand, deep copy corresponds to the method of copying via the copy method etc., and it behaves like copying the contents of the box as the meaning of "deep" in deep.

This difference between shallow copy and deep copy can be inadvertently mistaken when writing a program. For example, cases such as "the original value was supposed to be updated but not updated" and conversely "the original value was changed at an unexpected timing" are applicable. ..

Why aren't they all deep copies? Isn't it confusing? However, it is certainly confusing and tends to induce mistakes. However, if deep copy is executed every time, it will be a heavy burden on the personal computer etc. depending on the size of the contents such as the list.

For example, a list can store millions or tens of millions of values. This can be very burdensome if deep copies are performed frequently. Therefore, it is usually treated as a shallow copy, and only when a deep copy is required, the copy method etc. is explicitly called to make a deep copy.

I understand shallow copy and deep copy as a concept, and even if I continue programming for a long time, I rarely make mistakes, so be careful.

Check the number of occurrences of an element in the list: count method

The count method calculates the number of specific values contained in the list. Specify the target value in the first argument.

For example, if you specify'cat'as the first argument, the number of values'cat' in the list will be returned.

list_value = ['Cat', 'dog', 'Cat', 'Cat', 'dog']
print(list_value.count('Cat'))

Output contents of code execution result:

3

Find out at which index the element of interest is located: index method

Use the index method to find out at what index a particular element is in the list.

Specify the element you want to search in the first argument, and the result index will be set in the return value.

Index values start at 0 like any other, so they are set to 0 index for the first, 1 index for the second, 2 index for the third, and so on.

list_value = ['dog', 'rabbit', 'Cat', 'dog']
print('Index with the value of cat:', list_value.index('Cat'))

Output contents of code execution result:

Index with the value of cat: 2

If there are multiple target values, the first index is returned.

list_value = ['dog', 'rabbit', 'Cat', 'dog', 'Cat']
print('Index with the value of cat:', list_value.index('Cat'))

Output contents of code execution result:

Index with the value of cat: 2

An error will occur if a value not included in the list is specified as an argument.

ValueError: 'Cat' is not in list

I get an error message like "The value'cat'is not in the list".

Reference site / literature summary

-Clear, pop, remove, del to remove list (array) elements in Python -Difference between shallow copy and deep copy

Recommended Posts

Summary of built-in methods in Python list
Summary of Python3 list operations
How to get a list of built-in exceptions in python
Summary of various for statements in Python
Summary of how to use Python list
List of python modules
Filter List in Python
List find in Python
Summary of Python arguments
[Python] Sort the list of pathlib.Path in natural sort
Summary of how to import files in Python 3
List of frequently used built-in functions and methods
Make a copy of the list in Python
Summary of how to use MNIST in Python
Summary of Excel operations using OpenPyXL in Python
Summary of tools needed to analyze data in Python
Summary of python file operations
What's new in Python 3.10 (Summary)
String object methods in Python
Summary of Python sort (list, dictionary type, Series, DataFrame)
[python] Get the list of classes defined in the module
[Python] Manipulation of elements in list (array) [Add / Delete]
List of nodes in diagrams
Equivalence of objects in Python
Summary of Pandas methods used when extracting data [Python]
List of Python code used in big data analysis
Methods available in the list
Python: Get a list of methods for an object
Face detection summary in Python
Group by consecutive elements of a list in Python
Dynamically call methods in Python
Implementation of quicksort in Python
What's new in Python 3.9 (Summary)
Getting list elements in Python
Summary of date processing in Python (datetime and dateutil)
Summary of statistical data analysis methods using Python that can be used in business
[Introduction to Python] Summary of functions and methods that frequently appear in Python [Problem format]
Basic summary of data manipulation in Python Pandas-Second half: Data aggregation
[For beginners] Summary of standard input in Python (with explanation)
Get the number of specific elements in a python list
I measured various methods of interprocess communication in multiprocessing of python3
Decrypt one line of code in Python lambda, map, list
Get index of nth largest / smallest value in list in Python
[Python] List of major destructive methods of list operation (addition / deletion / sorting)
Get index of nth largest / smallest value in list in Python
Extract multiple list duplicates in Python
Pixel manipulation of images in Python
Difference between list () and [] in Python
[python] Manage functions in a list
Output 2017 Premium Friday list in Python
A brief summary of Python collections
MySQL-automatic escape of parameters in python
Handling of JSON files in Python
Implementation of life game in Python
Waveform display of audio in Python
Summary of various operations in Tensorflow
Dynamically define functions (methods) in Python
Law of large numbers in python
Implementation of original sorting in Python
Reversible scrambling of integers in Python
Delete multiple elements in python list