The contents of the Python tutorial (Chapter 5) are itemized.

Previous article: The contents of the Python tutorial (Chapter 4) are itemized

Introduction

Python3 Engineer Certification Basic Exam As a countermeasure, this is a personal memo that summarizes the contents of the Python tutorial (book) in easy-to-memorize bullet points.

Reference material

Python Tutorial: https://docs.python.org/ja/3/tutorial/ Chapter 5: https://docs.python.org/ja/3/tutorial/datastructures.html Books: https://www.oreilly.co.jp/books/9784873117539/

"Chapter 5 Data Structure"

--Python3 Engineer Certification Basic Exam Score ―― 7/40 questions (17.5%) ☆☆☆☆ ★ (Importance: Medium +) --Theme --List --Tuple --Set --Dictionary --Evaluation by comparison operator and Boolean operator --Comparison of sequences and other objects

5.1 Supplementary information about lists

--The following are all the methods of the list object.

Method name Description
list.append(x) Add an item with the value x to the end.
list.extend(L) Add all items in list L to the end.
list.insert(i, x) Add an item with the value x at the position of index i.
list.remove(x) Delete the item with the value x and the lowest index.
Error if the item does not exist.
list.pop([i]) Deletes and returns the item at index i.
The index can be omitted, and if omitted, the last item will be deleted / returned.
list.clear() Delete all items.
list.index(x) Returns the minimum index of the item whose value is x.
Error if the item does not exist.
list.count(x) Returns the number of items with a value of x.
list.sort(key=None, reverse=False) Sort items in place.
list.reverse() Reverse the items in place.
list.copy() Returns a shallow copy of the list.

5.1.1 Use list as stack

--The stack is last-in, first-out. --Use append (x) to push it onto the stack. --Use pop () to get from the stack. --It is fast because it is an operation at the end of the list.

5.1.2 Use list as queue

--Queues are first-in, first-out. --Use insert (0, x) to queue. --Use pop () to get from the queue. --Since it is the operation at the top of the list, it is slow. --Cue implementation should use collections rather than lists.

5.1.3 List comprehension

-** List comprehension ** consists of an expression followed by a for clause, followed by 0 or more for clauses and if clauses, and the whole is enclosed in []. -* squares = * * [x \ * \ * 2 for x in range (10)] * # 0 \ * \ * 0 ~ 9 \ * \ * 9 list comprehension --List comprehensions can contain compound expressions and nested functions. --Common usage of list comprehension --Processing each member of a sequence or repeatable body to generate a new list --Create a subsequence by extracting the elements that match the conditions

5.1.4 Nested list comprehension

--Any expression can be used for the first expression in the list comprehension. --Nested list comprehension (put another list comprehension in the first expression) is also possible.

5.2 del statement

-You can use the ** del statement ** to index items in the list.
Variables can also be deleted. -* del a [0] * # Delete item with index 0 -* del a [2: 4] * # Deleted items with indexes 2 and 3 -* del a [:] * # Delete all items -* del a * # Delete variable a --Unlike pop (), it does not return deleted items. --remove () removes the first item whose argument and value match.

5.3 Tuples and sequences

-** Tuples ** are a type of sequence, consisting of comma-separated values. -Index and slice operations are possible as well as strings and lists. --Defining tuples is called tuple packing. -* t = (12345, 54321,'hello!') * # () Can be omitted -* empty = () * # Tuple with 0 items -* singleton ='hello', * # Tuple with 1 item (comma at the end is the point) --When you output a tuple, it is enclosed in (). --Print (t) # (12345, 54321,'hello!') --Assigning tuple items to individual variables is called ** sequence unpacking . - x, y, z = t * # Variable x is assigned 12345, y is assigned 54321, and z is assigned'hello!'. --Match the number of variables and the number of tuple items. --Multiple assignment ** can be done using unpacking. - x, y, z = 1, 2, 3 * # Substitute the tuple (1, 2, 3) value for each tuple (x, y, z) item --Differences between tuples and lists --It is an immutable body (immmutable). --Items can include modifiable objects such as lists. --Each item is generally accessed by unpacking or indexing. --Items of different data types are often mixed.

5.4 Set

-** Set ** is a collection of elements that do not overlap in any order. --Python has a ** set object **, which is created using the {} and ** set () functions **. --Use set () to generate the empty set. --You can write ** set comprehension ** as well as list comprehension. - a = {x for x in 'abracadabra' if x not in 'abc'} --Supports mathematical operations such as sum, intersection, difference, and symmetric difference.

Set arithmetic Description
a in x
[Existence judgment]
True if the set a has an element x(true)
If not False(false)
a | b
[sum]
A set of elements at a or b
a - b
[difference]
A set of elements that are in a but not in b
a & b
[Crossing]
A set of elements in both a and b
a ^ b
[Symmetric difference]
A set of dissimilar elements in a or b

5.5 Dictionary

-** Dictionary ** is an unsorted collection of "key: value" pairs. - tel = {'jack': 4098, 'sape': 4139} -* print (tel ['jack']) * Returns # 4098 -* print (tel) * # {'jack': 4098,'sape': 4139} is returned -* empty = {} * # empty dictionary --Keys cannot be duplicated, and any immutable body can be used. --String --Numerical value --Tuples (do not include mutable objects) --Specify a key for addition, deletion, and existence confirmation to the dictionary. -* tel ['guido'] = 4127 * # tel will be added with'guido': 4127 -* del tel ['jack'] * # tel removes'jack': 4098 -'sape' in tel * # Existence: True -'test' in tel * # Existence: False -** You can get the iterable of the key list with the keys () method . - keylist = list (tel.keys ()) * # Get key list in list format - keysort = sorted (tel.keys ()) * # Get the key list in sorted list format --By the way, although it is not in the tutorial, you can get a list of values with the ** values () method . - dict () Constructor ** can be used to create a dictionary from tuples. -* tel = dict ([('jack', 4098), ('sape', 4139)]) * # tel = {'jack': 4098,'sape': 4139} --Like lists and tuples, there are also ** dictionary comprehensions *. - dic = {x: x \ ** 2 for x in (2, 4, 6)} * # dic = {2: 4, 4: 16, 6: 36} Same as

5.6 Loop technique

--The dictionary's ** items () method ** can be used to get a tuple list (repeatable) of (key, value). -** You can get a tuple list (repeatable body) of (index, value) by passing a sequence to the enumerate () function . - If you pass two or more sequences to the zip () function **, you can get a tuple list (repeatable body) of (sequence 1 value, sequence 2 value ...). -You can get a list of items (repeated bodies) in reverse index order by passing a sequence to the ** reversed () function **. --The contents of the original sequence are not rewritten. --Note that unlike sort () below, the list is not returned. -You can get a new sorted list of items by passing a sequence to the ** sort () function **. --The contents of the original sequence are not rewritten.

5.7 Supplementary information about conditions

--There are ** numeric operator **, ** comparison operator **, and ** Boolean operator ** as operators used to judge conditions. --The condition judgment result can be denied by ** not **.

operator Description
Comparison operator ==, !=, <, <=, >=, >There are other than
a in x True if a is included in sequence x(true)
a not in x True if a is not included in sequence x(true)
a is x True if a and b are the same instance(true)
a is not x True if a and b are not the same instance(true)
Boolean operator Alias, short circuit operator
A and B Both A and B are True(true)Then True(true)
A or B A or B is True(true)Then True(true)
not A A is True(true)Then False(false)
A is False(false)Then True(true)

--The priority of operators is numeric operator> comparison operator> not> and> or You can control the priority by enclosing it in (). --Comparison operators can be ** chained *. - if a <b == c: * # (a <b) and (b == c) --The Boolean operator evaluates from right to left and ends when the evaluation is decided. - A and B and C --If A and B are False, and C is not evaluated - A or B or C --If A or B is True, or C is not evaluated --If a general value is used instead of a Boolean value, the return value of the short circuit operator will be the last evaluated argument. --The result of a Boolean expression such as comparison can be assigned to a variable. --You cannot assign in an expression.

5.8 Sequence comparison, other type comparison

--The size comparison of sequence type objects is evaluated by the following steps.

  1. Compare items with index 0 and evaluate the larger one as "large".
  2. If the items are the same size, increase the index by +1 and compare the next items.
  3. Repeat step 2 until you find items of different sizes or one of them ends. --If both items are the same size, they are judged to be the same size. --If one of them reaches the end first, it is evaluated as "small". --The magnitude relation of character strings is compared by Unicode code point number. --If the items in the sequence are sequences, the items are also compared according to the same rules. --Comparison between objects of different types basically returns a ** TypeError exception **. --Comparison between numerical values (int and float, etc.) is possible. --In some cases, you can use the appropriate comparison method provided by the object.

Next article: The contents of the Python tutorial (Chapter 6) are itemized

Recommended Posts

The contents of the Python tutorial (Chapter 5) are itemized.
The contents of the Python tutorial (Chapter 4) are itemized.
The contents of the Python tutorial (Chapter 2) are itemized.
The contents of the Python tutorial (Chapter 8) are itemized.
The contents of the Python tutorial (Chapter 1) are itemized.
The contents of the Python tutorial (Chapter 10) are itemized.
The contents of the Python tutorial (Chapter 6) are itemized.
The contents of the Python tutorial (Chapter 3) are itemized.
Get the contents of git diff from python
the zen of Python
Not being aware of the contents of the data in python
Reproduce the execution example of Chapter 4 of Hajipata in Python
[Maya Python] Crush the contents of the script 2 ~ list Notes
Reproduce the execution example of Chapter 5 of Hajipata in Python
Towards the retirement of Python2
About the ease of Python
About the features of Python
Simulation of the contents of the wallet
The Power of Pandas: Python
About the matter that the contents of Python print are not visible in docker logs
[Maya Python] Crush the contents of the script 3 ~ List unknown Plugins
[Maya Python] Crush the contents of the script 1 ~ Camera Speed Editor
[Data science memorandum] Confirmation of the contents of DataFrame type [python]
A Python script that compares the contents of two directories
How to check if the contents of the dictionary are the same in Python by hash value
The story of Python and the story of NaN
Easy encryption of file contents (Python)
[Python] The stumbling block of import
[Python of Hikari-] Chapter 09-03 Class (inheritance)
First Python 3 ~ The beginning of repetition ~
[Python] [Table of Contents Links] Python Programming
Understand the contents of sklearn's pipeline
[Translation] scikit-learn 0.18 Tutorial Table of Contents
Existence from the viewpoint of Python
pyenv-change the python version of virtualenv
Change the Python version of Homebrew
See the contents of Kumantic Segumantion
Python Math Series ⓪ Table of Contents
[Python] Understanding the potential_field_planning of Python Robotics
Review of the basics of Python (FizzBuzz)
Introductory table of contents for python3
About the basics list of Python basics
Learn the basics of Python ① Beginners
[python, ruby] fetch the contents of a web page with selenium-webdriver
Output the contents of ~ .xlsx in the folder to HTML with Python
[Python of Hikari-] Chapter 07-02 Exception handling (continuous execution of the program by exception handling)
Verification of the theory that "Python and Swift are quite similar"
Contents of reading VBA x Python fastest work technique Memo chapter1
[Python] A program that rotates the contents of the list to the left
I checked the contents of docker volume
Change the length of Python csv strings
Check the behavior of destructor in Python
[Python3] Understand the basics of Beautiful Soup
Pass the path of the imported python module
The story of making Python an exe
Learning notes from the beginning of Python 1
Check the existence of the file with python
About the virtual environment of python version 3.7
[Python] Understand the content of error messages
Python tutorial
[Introduction to Python] How to sort the contents of a list efficiently with list sort