[Python] Chapter 04-02 Various data structures (list manipulation)

[Python] Chapter 04-02 Manipulating Lists

Here, I would like to learn about operations such as adding and deleting elements from the created list. Since it means to operate, basically we will use the method.

First, create the previous list. This time as well, we will create it using the ** Python Console **.

>>>ls = ['Japan', 'Canada', 'Australia', 'England', 'German', 'Italy', 'France']
>>>print(ls)
['Japan', 'Canada', 'Australia', 'England', 'German', 'Italy', 'France']

Add elements to the list

There are two ways to add an element. Let's look at each one.

(1) Use of append method

Consider adding an element to the list you created ** ls **. Use the ** append ** method to add an element. In other words, we will investigate the variable ls with the method append. Let's add an element called'America'to ** ls **. Enter the code below. First check the contents with ls, then try adding.

>>>ls
['Japan', 'Canada', 'Australia', 'England', 'German', 'Italy', 'France']
>>>ls.append('America')
>>>ls
['Japan', 'Canada', 'Australia', 'England', 'German', 'Italy', 'France', 'America']

Finally, type ls to check the contents of ls, and the element'America'added by the append method will be added to the list.

(2) Use of extend method

I have confirmed that the append method can add an element to the list. So how do you add more than one at a time?

Use the ** extend ** method to add multiple elements. Specifically, I would like to confirm by typing the code as follows. Check the contents of ** ls ** as before, and then execute.

>>>ls
['Japan', 'Canada', 'Australia', 'England', 'German', 'Italy', 'France', 'America']
>>>ls.extend(['India','Spain'])
>>>ls
['Japan', 'Canada', 'Australia', 'England', 'German', 'Italy', 'France', 'America', 'India', 'Spain']

The extend method specifies the inside of () as a list like ** ['India','Spain'] **.

Note that the append method and extend method make the difference between adding one element or adding two or more elements. If you make a mistake, an error will occur.

Remove elements from list

Let's see how to remove an element from the list. There are three ways.

(1) Use of remove method

The ** remove ** method directly specifies and removes an element in the list.

Enter the following in the ** Python Console **: Check the contents of ** ls ** as before, and then execute.

>>>ls
['Japan', 'Canada', 'Australia', 'England', 'German', 'Italy', 'France', 'America', 'India', 'Spain']
>>>ls.remove('Canada')
>>>ls
['Japan', 'Australia', 'England', 'German', 'Italy', 'France', 'America', 'India', 'Spain']

As mentioned above, I was able to confirm that'Canada' was deleted. In the case of the remove method, the content of the element is directly specified instead of the element number to remove it.

If there are the same values in the list, deleting the value will delete the first one that appears.

>>>numL = [5, 7, 4, 5, 9]
>>>numL.remove(5)
>>>numL
[7, 4, 5, 9]

(2) Use of del statement

It doesn't use a method, but I'll show you a ** del statement ** as a way to delete the same list element.

Enter the following in the ** Python Console **: Check the contents of ** ls ** as before, and then execute.

>>>ls
['Japan', 'Australia', 'England', 'German', 'Italy', 'France', 'America', 'India', 'Spain']
>>>del ls[3]
>>>ls
['Japan', 'Australia', 'England', 'Italy', 'France', 'America', 'India', 'Spain']

In the case of ** del statement **, the deletion is performed by specifying the element number, not by specifying the element. This time, I specified del ls [3], so the third'German' was deleted. ** (Of course, the element number starts from 0 this time as well) **

(3) Use of clear method

One thing to keep in mind when using the clear method is to remove all the elements in the list. However, the list itself does not disappear and becomes an empty list.

Enter the following in the ** Python Console **: Check the contents of ** ls ** as before, and then execute.

>>>ls
['Japan', 'Australia', 'England', 'Italy', 'France', 'America', 'India', 'Spain']
>>>ls.clear()
>>>ls
[]

Search the list

Let's see how to search for the specified element in the list. Before the explanation, I will make a new list. Now let's create a list of numbers and explain.

>>>numL = [60, 80, 70, 90, 50]
>>>numL
[60, 80, 70, 90, 50]

(1) Use of index method

The ** index ** method returns the position of the specified element. Enter the following in the ** Python Console **: Check the contents of ** numL ** as before, and then execute.

>>>numL
[60, 80, 70, 90, 50]
>>>numL.index(70)
2

Since we have specified the method as index (70) this time, we will search for 70 positions in the list. Then we know that it is second, so we return 2.

Of course, if you specify an element that does not exist, an error will occur as shown below.

>>>numL.index(100)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: 100 is not in list

(2) How to check the presence or absence by in, not in

This is not a method using a method, but a method to check whether the specified element exists in the list by using ** in **.

Enter the following in the ** Python Console **: Check the contents of ** numL ** as before, and then execute.

>>>numL
[60, 80, 70, 90, 50]
>>>70 in numL
True
>>>100 in numL
False

** 70 in numL ** asks the question "Is there a value of 70 in the list of numL?" And the result is ** True **. Also, ** 100 in numL ** asks the question "Is there a value of 100 in the list of numL?" And the result is ** False **.

And conversely, using not in, ** does it exist? You can also check **.

Enter the following in the ** Python Console **: Check the contents of ** numL ** as before, and then execute.

>>>numL
[60, 80, 70, 90, 50]
>>>70 not in numL
False
>>>100 not in numL
True

** 70 not in numL ** asks the question "Is there a value of 70 in the list of numL?" And the result is ** False **. Also, ** 100 not in numL ** asks the question "Is there a value of 100 in the list of numL?" And the result is ** True **.

In addition, ** True ** and ** False ** that came out this time are one of the classifications such as integer type and character string type called Boolean type. It will appear in control syntax such as if statement and while statement, which will be explained in the future.

Sorting list elements

This section describes how to sort the elements in the list. The method is a method using a function and a method using a method.

(1) Use of sorted function

The ** sorted function ** allows you to sort the elements of the list in ascending (or descending) order.

Enter the following in the ** Python Console **: Check the contents of ** numL ** as before, and then execute.

>>>numL
[60, 80, 70, 90, 50]
>>>sorted(numL)
[50, 60, 70, 80, 90]
sorted(numL, reverse=True)
[90, 80, 70, 60, 50]

First, the inside of () of the sorted function is called ** argument (hikisu) **, and you can sort by putting a list in this argument. Also, if you specify reverse = True after the argument, it will be sorted in descending order.

In the above state, I would like to display the contents of ** numL ** again.

>>>numL
[60, 80, 70, 90, 50]

From this result, you can see that the ** function does not change numL itself **.

(1) Use of sort method

By specifying the ** sort method **, the contents of the list can be sorted in the same way as the sorted function. Enter the following in the ** Python Console **: Check the contents of ** numL ** as before, and then execute.

>>>numL
[60, 80, 70, 90, 50]
>>>numL.sort()
>>>numL
[50, 60, 70, 80, 90]

I found that the sort method can sort the values, but it doesn't output as it is. To check it, you need to check the contents of numL.

In addition, in the case of the sorted function, numL itself was not sorted even if it was sorted, but in the case of the sort method, it can be confirmed that numL itself is sorted.

Finally

Today, many methods for lists have appeared. It's worth remembering the basic methods, but it's also a good idea to look into things like specifying detailed arguments.

List-related methods (https://docs.python.org/ja/3/tutorial/datastructures.html)

Return to [Table of Contents Link]

Recommended Posts

[Python] Chapter 04-02 Various data structures (list manipulation)
[Python] Chapter 04-03 Various data structures (multidimensional list)
[Python] Chapter 04-04 Various data structures (see list)
[Python] Chapter 04-07 Various data structures (dictionary manipulation)
[Python] Chapter 04-06 Various data structures (creating dictionaries)
[Python] Chapter 04-01 Various data structures (list creation and element retrieval)
[Python] Chapter 04-05 Various data structures (tuple creation and features)
Python list manipulation
[Python] [Supplement] Chapter 04-08 Various data structures (creating and manipulating sets)
[Python] [Supplement] Chapter 04-09 Various data structures (set theory and operations in sets)
Python for Data Analysis Chapter 4
Python for Data Analysis Chapter 2
Python for Data Analysis Chapter 3
Python data structures learned with chemoinformatics
[Python] list
Python Application: Data Visualization Part 3: Various Graphs
Ant book in python: Sec. 2-4, data structures
Python data structure and internal implementation ~ List ~
[Introduction to Python3 Day 19] Chapter 8 Data Destinations (8.4-8.5)
[Introduction to Python3 Day 18] Chapter 8 Data Destinations (8.3.6.2 to 8.3.6.3)
[Python] Various data processing using Numpy arrays
Let's do MySQL data manipulation with Python
[Python] List Comprehension Various ways to create a list
Python Grammar-String Manipulation
[python] Create a list of various character types
Data analysis python
PySpark data manipulation
Python> Comprehension / Comprehension> List comprehension
Python Application: Data Handling Part 2: Parsing Various Data Formats
[python] Read data
List of Python libraries for data scientists and data engineers
[Python] Manipulation of elements in list (array) [Add / Delete]
[Technical book] Introduction to data analysis using Python -1 Chapter Introduction-
Sorted list in Python
Python Exercise 2 --List Comprehension
Data analysis with python 2
List of python modules
Python> list> extend () or + =
Python Node.js character manipulation
Python Data Visualization Libraries
String manipulation in python
Data analysis using Python 0
Python list comprehension speed
Date manipulation in Python
python unittest assertXXX list
Python string manipulation master
Data cleaning using Python
Python3 List / dictionary memo
OpenCV3 Python API list
Python error list (Japanese)
List find in Python
Data manipulation with Pandas!
Python data analysis template
[Python tutorial] Data structure
[Python] Sorting Numpy data
[Python] Chapter 01-01 About Python (First Python)
Data analysis with Python
Python exception class list
Various processing of Python
Initialize list with python
Basic summary of data manipulation in Python Pandas-Second half: Data aggregation