Memo # 6 for Python beginners to read "Detailed Python Grammar"

Back number

-Memo # 1 for Python beginners to read "Detailed explanation of Python grammar" -Memo # 2 for Python beginners to read "Detailed Explanation of Python Grammar" -Memo # 3 for Python beginners to read "Detailed explanation of Python grammar" -Memo # 4 for Python beginners to read "Detailed explanation of Python grammar" -Note that a Python beginner read "Detailed explanation of Python grammar" # 5

Python list references an object


>>> L1 = [1, 2]
>>> L2 = ['A', L1]
>>> L2
['A', [1, 2]]
>>> L1.append('three')
>>> L2
['A', [1, 2, 'three']]

#To elementize as a separate object instead of a reference
>>> L1 = [1, 2]
>>> L2 = ['A', L1[:]]
>>> L2
['A', [1, 2]]
>>> L1.append('three')
>>> L2
['A', [1, 2]]

List comprehension#1


#List processing like this
src = ['SPAM', 'HAM', 'EGG']
dest = []
for val in src:
    lowerer = val.lower()
    dest.append(lowerer)  #Make it all lowercase and plunge into another list

#Python can be written like this. Easy.
src = ['SPAM', 'HAM', 'EGG']
dest = [val.lower() for val in src]

List comprehension seems to be faster. Python list comprehension speed

List comprehension#2


#It is also possible to generate a list by specifying a conditional expression
>>> L = [1, 2, 3, 4, 5]
>>> [i for i in L if i % 2]
[1, 3, 5]

#Iterable object elements can also be decomposed and stored
>>> L = [('a', 1), ('b', 2), ('c', 3)]
>>> [c * i for c, i in L]
['a', 'bb', 'ccc']

#At the beginning of the variable name*If you add, you can receive multiple elements in a list
>>> L = [(1, 2), (3, 4, 5), (6, 7, 8, 9)]
>>> [first * sum(others) for first, *others in L]
[2, 27, 144]

#Multiple loops are also possible
>>> years = [2019, 2020]
>>> months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> [(y, m) for y in years
...     for m in months]
[(2019, 1), (2019, 2), (2019, 3), (2019, 4), (2019, 5), (2019, 6), (2019, 7), (2019, 8), (2019, 9), (2019, 10), (2019, 11), (2019, 12), (2020, 1), (2020, 2), (2020, 3), (2020, 4), (2020, 5), (2020, 6), (2020, 7), (2020, 8), (2020, 9), (2020, 10), (2020, 11), (2020, 12)]

Since the list is a sequence type object, Operators such as + (concatenation), * (repetition), and comparison operators are supported

List operator


#Linking
>>> [1, 2] + [3]
[1, 2, 3]

#repetition
#If you prepare a fixed length list in advance, it looks like this
>>> L = [None] * 5
>>> L
[None, None, None, None, None]

Of the sequence+Operators and*The operator just copies the reference


#If you want to create a list object with multiple list objects as elements
#I feel like I can write like this
>>> L = [[]] * 3
>>> L
[[], [], []]

#But no
>>> L[0].append(1)
>>> L
[[1], [1], [1]]  #All elements are references to the same object

#List comprehension notation at such times
>>> L = [[] for i in range(3)]
>>> L[0].append('spam')
>>> L
[['spam'], [], []]

List cumulative assignment statement


#For list objects, A= A +B and A+=B is not equivalent!
>>> A = [0, 1, 2, 3]
>>> B = ['spam']
>>> id(A)
4429687688
>>> A = A + B
>>> A
[0, 1, 2, 3, 'spam']
>>> id(A)
4429687176  # A = A +In B, a new list object is assigned to A


>>> A = [0, 1, 2, 3]
>>> B = ['spam']
>>> id(A)
4429687688
>>> A += B
>>> A
[0, 1, 2, 3, 'spam']
>>> id(A)
4429687688  # A +=In B, all the elements of B are added as they are to the list object indicated by variable A.

You don't have to put together the methods, but write them in the sense of trying them once.

List methods here and there


#Add element
>>> A = [0, 1, 2, 3]
>>> A.append(4)
>>> A
[0, 1, 2, 3, 4]
#However, if the number of elements is known in advance, it is faster to use substitution or inclusion notation.
#reference:https://www.kumilog.net/entry/python-speed-comp

#Delete all elements
>>> A = [0, 1, 2, 3]
>>> A.clear()  # del A[:]Same as
>>> A
[]

#Create another list object with the same elements
>>> A = [0, 1, 2, 3]
>>> id(A)
4429688712
>>> B = A.copy()  # B = A[:]Same as
>>> B
[0, 1, 2, 3]
>>> id(B)
4430184776

#Returns the number of elements with a value equal to the argument
>>> A = [0, 1, 2, 1]
>>> A.count(1)
2

#Decompose and append all elements of an iterable object
>>> A = [0, 1, 2]
>>> A.extend('spam')
>>> A
[0, 1, 2, 's', 'p', 'a', 'm']
>>> A[len(A):len(A)] = 'ham'  #This is the same
>>> A
[0, 1, 2, 's', 'p', 'a', 'm', 'h', 'a', 'm']

#Finds an element with a value equal to the argument and returns the index of the first matching element
>>> A = [3, 4, 5, 3, 4, 5]
>>> A.index(4)
1
>>> A.index(4, 3)     #The search range can be specified as an argument in the manner of slicing
4
>>> A.index(4, 3, 4)  #Exception if not
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 4 is not in list

#Add element to specified position
>>> L = ['ham']
>>> L.insert(0, 'spam')  # L[0:0] = ['spam']Same as
>>> L
['spam', 'ham']
>>> L.insert(-1, 'egg')  #Added to relative position from the end
>>> L
['spam', 'egg', 'ham']

#Pop the trailing element (return its value and delete the element)
>>> L = [0, 1, 2, 3]
>>> L.pop()
3
>>> L
[0, 1, 2]
>>> L.pop(1)  #Index can be specified
1
>>> L
[0, 2]

#Search for elements with the same value as the argument and remove the first matching element
>>> L = [0, 1, 2, 3, 2]
>>> L.remove(2)
>>> L
[0, 1, 3, 2]

#Replace the elements in the list in reverse order. It doesn't create a new list object.
>>> L = [0, 1, 2, 3]
>>> L.reverse()
>>> L
[3, 2, 1, 0]

#Sort the elements of the list. Do not create a new list object. Arguments are for keywords only.
>>> L = ['9', '10', '100']
>>> L.sort()
>>> L
['10', '100', '9']

#If a function is specified for key, the key is called with the list element as an argument and the return value is sorted as the key.
>>> L.sort(key=int)
>>> L
['9', '10', '100']

#Descending sort
>>> L.sort(reverse=True)
>>> L
['9', '100', '10']

#Sorting in python is "stable sorting" (elements with the same sort key do not change before and after sorting)
>>> def func(v):return v % 3
... 
>>> L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> L.sort(key=func)
>>> L
[3, 6, 9, 0, 1, 4, 7, 2, 5, 8]  # 3,6,9 - 0,1,4,7 - 2,5,The context of 8 has not changed

Recommended Posts

Memo # 4 for Python beginners to read "Detailed Python Grammar"
Memo # 3 for Python beginners to read "Detailed Python Grammar"
Memo # 1 for Python beginners to read "Detailed Python Grammar"
Memo # 2 for Python beginners to read "Detailed Python Grammar"
Memo # 7 for Python beginners to read "Detailed Python Grammar"
Memo # 6 for Python beginners to read "Detailed Python Grammar"
Memo # 5 for Python beginners to read "Detailed Python Grammar"
Basic Python grammar for beginners
~ Tips for beginners to Python ③ ~
Memo to ask for KPI with python
Beginners read "Introduction to TensorFlow 2.0 for Experts"
[Python] Read images with OpenCV (for beginners)
The fastest way for beginners to master Python
For beginners to build an Anaconda environment. (Memo)
Python for super beginners Python for super beginners # Easy to get angry
python textbook for beginners
Try to calculate RPN in Python (for beginners)
Python basic grammar memo
Introduction to Programming (Python) TA Tendency for beginners
How to make Python faster for beginners [numpy]
[For beginners] How to study programming Private memo
OpenCV for Python beginners
[For beginners] How to use say command in python!
How to convert Python # type for Python super beginners: str
[For beginners] How to study Python3 data analysis exam
[For beginners] Learn basic Python grammar for free in 5 hours!
Python # How to check type and type for super beginners
Python memo (for myself): Array
Python Basic Grammar Memo (Part 1)
Python code memo for yourself
Python3 environment construction (for beginners)
3 Reasons Beginners to Start Python
Python basic grammar (miscellaneous) Memo (3)
Python basic grammar (miscellaneous) Memo (2)
100 Pandas knocks for Python beginners
[Python] Sample code for Python grammar
Python for super beginners Python #functions 1
Python #list for super beginners
Python basic grammar (miscellaneous) Memo (4)
Introduction to Python For, While
Tips for Python beginners to use Scikit-image examples for themselves 4 Use GUI
[For beginners] How to read Numerai's HP + Submit + Convenient links
[R] [Python] Memo to read multiple csv files in multiple zip files
Tips for coding short and easy to read in Python
[For beginners] Script within 10 lines (4. Connection from python to sqlite3)
Tips for Python beginners to use the Scikit-image example for themselves
[Python] Introduction to graph creation using coronavirus data [For beginners]
Python Exercise for Beginners # 2 [for Statement / While Statement]
Minimum grammar notes for writing Python
Python #index for super beginners, slices
<For beginners> python library <For machine learning>
Python #len function for super beginners
Beginners use Python for web scraping (1)
[Nanonets] How to post Memo [Python]
Run unittests in Python (for beginners)
Beginners use Python for web scraping (4) ―― 1
Python #Hello World for super beginners
Python for super beginners Python # dictionary type 2 for super beginners
An introduction to Python for non-engineers
python beginners tried to find out
Python learning memo for machine learning by Chainer Chapter 8 Introduction to Numpy