Python built-in object

Overview

Study notes for First Python 3rd Edition

agenda

--Built-in object --Numerical value --String --List --Dictionary --Tuple

Built-in object

Benefits of using built-in objects

--Easy to program --You can also create your own objects based on the built-in objects --Built-in objects often perform better than custom objects --Python's built-in objects are written in C and are pre-optimized for high performance. --Built-in objects are standard --Characteristics and functions do not change

Built-in object type

Object type Literal example
Numerical value 1234
3.1425
999L
3+4j
String 'spam'
"guido7s"
list [1, [2, 'three'], 4]
dictionary {'food': 'spam', 'taste': 'yum'}
Tuple (1, 'spam', 4, 'U')
File myfile = open('eggs', 'r')
Other set
type
None
bool

Numerical value

Mathematical arithmetic

Use the + symbol for addition, the * for multiplication, and the ** symbol for exponentiation.

#Integer addition
>>> 123 + 222
345

#Floating point multiplication
>>> 1.5 * 4
6.0

#2 to the 100th power
#Python automatically converts to "long integers" when precision needs to be improved.
>>> 2 ** 100
1267650600228229401496703205376L

The following differences are between the two built-in functions repr and str

#repr: Display the calculation result as it is(Output with maximum accuracy)
>>> 3.1415 * 2
6.2830000000000004

#str: Convert to easy-to-read format and display(Display in a form that is easy for humans to see)
>>> print 3.1415 * 2
6.283

math module

--The math module provides tools in the form of functions that can be used for advanced processing related to numerical values.

>>> import math
>>> math.pi
3.1415926535897931
>>> math.sqrt(85)
9.2195444572928871

random module

--The random module has a random number generation function or a random selection function.

>>> import random
>>> random.random()
0.59268735266273953
>>> random.choice([1, 2, 3, 4])
1

String

sequence

--A string is a type of object called a sequence --A sequence is an arrangement of objects in a certain order. --In a sequence, the order of the element objects does not always change

Manipulating sequences

--The index is a number that indicates the number of elements from the left end. --The index of the first element is "0" and the second is "1". --By using a negative number, you can specify the elements in reverse order from the right end. --In addition to specifying numbers, you can also write expressions in square brackets. ――Supports the operation of slicing, which has a wider range of applications --Slicing is the process of cutting out a specific part of a character string and examining its contents. --Can be concatenated by using the + symbol --You can iterate by using the * symbol

>>> S = 'Spam'

#Check the length
>>> len(S)
4

#If the index "0" is specified, the first element can be extracted.
>>> S[0]
'S'

#Extract the second element from the left
>>> S[1]
'p'

#Rightmost element of S
>>> S[-1]
'm'

#The second element from the right end of S
>>> S[-2]
'a'

#The last element of S
>>> S[-1]
'm'

#Same meaning, but more difficult here
>>> S[len(S)-1]
'm'

#Extract 1 and 2 elements (3 is not included) by slicing
>>> S[1:3]
'pa'

#Extract all elements after index 1 (1):len(S)Same as)
>>> S[1:]
'pam'

#There is no change in S itself after the above processing
>>> S
'Spam'

#Extract all elements except the end
>>> S[0:3]
'Spa'

# S[0:3]Same as
>>> S[:3]
'Spa'

#This is also the same (0:-You can write 1 but this is easier)
>>> S[:-1]
'Spa'

#Extract all elements of S (0:len(S)Same as)
>>> S[:]
'Spam'

#Linking
>>> S + 'xyz'
'Spamxyz'

#Original S does not change
>>> S
'Spam'

#repetition
>>> S * 8
'SpamSpamSpamSpamSpamSpamSpamSpam'

Invariant

--Even if you do something with the character string, the original character string does not change.

>>> S
'Spam'

#Objects with invariance cannot be overwritten
>>> S[0] = 'z'
...Error message omitted...
TypeError: 'str' object does not support item assignment

#Create a new string and assign it to the original variable
>>> S = 'z' + S[1:]
>>> S
'zpam'

String-specific methods

#Find the specified string
>>> S.find('pa')
1

>>> S
'Spam'

#Replace specified string
>>> S.replace('pa', 'XYZ')
'SXYZm'

>>> S
'Spam'

>>> line = 'aaa,bbb,ccccc,dd'

#Divide by delimiter to make a list
>>> line.split(',')
['aaa', 'bbb', 'ccccc', 'dd']

>>> S = 'spam'

#Case conversion
>>> S.upper()
'SPAM'

#Confirmation of contents (isalpha, isdigit, etc.)
>>> S.isalpha()
True

>>> line = 'aaa,bbb,ccccc,dd\n'

#Remove the rightmost whitespace
>>> line = line.rstrip()
>>> line
'aaa,bbb,ccccc,dd'

Variations on how to create strings

Escape sequence

# \n is the end of the line,\t is a tab
>>> S = 'A\nB\tC'

#Both are treated as one character
>>> len(S)
5

# \n corresponds to ASCII code 10.
>>> ord('\n')
10

# \0 represents NULL. Not the end of the string
>>> S = 'A\0B\0C'
>>> len(S)
5

Single, double and triple quotes

--If you enclose it in triple quotes, multiple lines will be treated as a group. --Convenient when embedding HTML or XML code in a Python program --If you prefix the leading quotation mark with "r", the backslash of the escape sequence will be interpreted as a simple character, which is called "raw string". --By adding "u" before the quotation mark, the character string inside can be interpreted as a Unicode character string.

>>> msg = """
aaaaaaaaaaaaa
bbb'''bbbbbbbbbb""bbbbbbb'bbbb
cccccccccccccc"""
>>> msg
'\naaaaaaaaaaaaa\nbbb\'\'\'bbbbbbbbbb""bbbbbbb\'bbbb\ncccccccccccccc'

Pattern matching

--Use a module called re

>>> import re
>>> match = re.match('Hello[ \t]*(.*)world', 'Hello Python world')
>>> match.group(1)
'Python '

>>> match = re.match('/(.*)/(.*)/(.*)', '/usr/home/lumberjack')
>>> match.groups()
('usr', 'home', 'lumberjack')

list

List features

--Not tied to a specific type --Size is not fixed

Sequence operation

--The same operation as a character string is possible —— Indexing and slicing are also possible

#A three-element list. All types are different
>>> L = [123, 'spam', 1.23]

#Number of elements in the list
>>> len(L)
3

#Indexing
>>> L[0]
123

#Slicing (resulting in a new list)
>>> L[:-1]
[123, 'spam']

#A new list is created even when concatenated
>>> L + [4, 5, 6]
[123, 'spam', 1.23, 4, 5, 6]

#The original list has not changed
>>> L
[123, 'spam', 1.23]

List-specific methods

--ʻAppend: Add element at the end --pop: Delete the element in the middle --ʻInsert: Insert element at specified position --remove: Remove the specified element --sort: Sort (overwrite) list elements in ascending order -- reverse: Reverse (overwrite) elements

#Add an element to the end to lengthen the list
>>> L.append('NI')
>>> L
[123, 'spam', 1.23, 'NI']

#Shorten the list by removing elements in the middle
>>> L.pop(2)
1.23

# “del L[2]"But you can delete the element
>>> L
[123, 'spam', 'NI']

>>> M = ['bb', 'aa', 'cc']
>>> M.sort()
>>> M
['aa', 'bb', 'cc']

>>> M.reverse()
>>> M
['cc', 'bb', 'aa']

Element existence check

To refer to an element that does not actually exist

>>> L
[123, 'spam', 'NI']

>>> L[99]
...Error message omitted...
IndexError: list index out of range

>>> L[99] = 1
...Error message omitted...
IndexError: list assignment index out of range

Nest

Nest application example

--Matrix --Multidimensional array

#A 3x3 matrix created by nesting lists
>>> M = [[1, 2, 3], 
         [4, 5, 6],
         [7, 8, 9]]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

#Access line 2
>>> M[1]
[4, 5, 6]

#After accessing row 2, get the third element of that row
>>> M[1][2]
6

List comprehension

--The list comprehension notation was devised based on the notation of set theory. --The operations are performed one by one from left to right. --Advantageous in terms of processing speed

#Extract the elements in the second column
>>> col2 = [row[1] for row in M]
>>> col2
[2, 5, 8]

#The original matrix remains unchanged
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

#Add 1 to each element in column 2
>>> [row[1] + 1 for row in M]
[3, 6, 9]

#Remove odd elements
>>> [row[1] for row in M if row[1] % 2 == 0]
[2, 8]

#Extract diagonal elements
>>> diag = [M[i][i] for i in [0, 1, 2]]
>>> diag
[1, 5, 9]

#Repeat the characters in the string
>>> doubles = [c * 2 for c in 'spam']
>>> doubles
['ss', 'pp', 'aa', 'mm']

dictionary

Map

--Dictionaries belong to the category of mapping, not "sequence" --The order in which the elements are arranged is not fixed --Among the main Python objects, only dictionaries belong to the mapping category. --Overwriteable "variable" objects ――Using a dictionary for the search process is the most advantageous in terms of speed.

Manipulating the map

>>> D = {'food': 'Spam', 'quantity': 4, 'color': 'pink'}

#Key'food'Specify
>>> D['food']
'Spam'

# 'quantity'Add 1 to the value corresponding to
>>> D['quantity'] += 1
>>> D
{'food': 'Spam', 'color': 'pink', 'quantity': 5}

>>> D = {}

#Assign a value by specifying a key that does not exist
>>> D['name'] = 'Bob'
>>> D['job'] = 'dev'
>>> D['age'] = 40
>>> D
{'age': 40, 'job': 'dev', 'name': 'Bob'}
>>> print D['name']
Bob

Nest

>>> rec = {'name': {'first': 'Bob', 'last': 'Smith'},
           'job': ['dev', 'mgr'],
           'age': 40.5}

# 'Name'Corresponds to a nested dictionary
>>> rec['name']
{'last': 'Smith', 'first': 'Bob'}

#Specify a nested dictionary key
>>> rec['name']['last']
'Smith'

# 'job'Corresponds to a nested list
>>> rec['job']
['dev', 'mgr']

#Specify index for nested list
>>> rec['job'][-1]
'mgr'

# 'job'Extend and overwrite the list corresponding to
>>> rec['job'].append('janitor')
>>> rec
{'age': 40.5,'job': ['dev', 'mgr', 'janitor'], 'name': {'last': 'Smith', 'first':'Bob'}}

Key Sort: for Loop

#Get a list of keys (in no particular order)
>>> Ks = D.keys()
>>> Ks
['a', 'c', 'b']

#Sort the list of keys
>>> Ks.sort()
>>> Ks
['a', 'b', 'c']

#Output the keys in the list and their corresponding values in order
>>> for key in Ks:
print key, '=>', D[key]
a => 1
b => 2
c => 3

The above process can be written as

>>> D
{'a': 1, 'c': 3, 'b': 2}
>>> for key in sorted(D):
print key, '=>', D[key]
a => 1
b => 2
c => 3

A for loop that converts the characters in the string to uppercase and outputs them.

>>> for c in 'spam':
print c.upper()
S
P
A
M

Iteration and optimization

――The following two codes are equivalent, but list comprehension is generally about twice as fast. --Emphasis should be placed on conciseness and readability, and processing speed should be considered afterwards. --If you need to check the speed, you can use tools such as time module, timeit module, profile module.

List comprehension


>>> squares = [x ** 2 for x in [1, 2, 3, 4, 5]]
>>> squares
[1, 4, 9, 16, 25]

for loop


>>> squares = []
>>> for x in [1, 2, 3, 4, 5]:
squares.append(x ** 2)
>>> squares
[1, 4, 9, 16, 25]

Non-existent key: if test

An error occurs when trying to access a value using a key that does not exist

>>> D
{'a': 1, 'c': 3, 'b': 2}

#Specifying a new key expands the dictionary
>>> D['e'] = 99
>>> D
{'a': 1, 'c': 3, 'b': 2, 'e': 99}

#Error when trying to access a value with a key that does not exist
>>> D['f']
...Error message omitted...
KeyError: 'f'

Make sure the key exists in advance

--Check if the key exists with the has_key method

>>> D.has_key('f')
False
>>> if not D.has_key('f'):
print 'missing'
missing

Tuple

Once created, it cannot be changed

>>> T = (1, 2, 3, 4) #Tuple with 4 elements
>>> len(T) #length
4
>>> T + (5, 6) #Linking
(1, 2, 3, 4, 5, 6)
>>> T[0] #Indexing, slicing, etc.
1
Perhaps the biggest difference from the tuple list is that once created, it cannot be modified.
>>> T[0] = 2 #Tuples are invariant
...Error message omitted...
TypeError: 'tuple' object does not support item assignment

Tuple

Tuple


#Tuple with 4 elements
>>> T = (1, 2, 3, 4)

#length
>>> len(T)
4

#Linking
>>> T + (5, 6)
(1, 2, 3, 4, 5, 6)

#Indexing, slicing, etc.
>>> T[0]
1

#The biggest difference from the tuple list is that once created it cannot be changed.
>>> T[0] = 2
...Error message omitted...
TypeError: 'tuple' object does not support item assignment

Why you need tuples

--To ensure consistency --Speed aspect

File

basic operation

writing


#Create new file in output mode
>>> f = open('data.txt', 'w')

#Write a string
>>> f.write('Hello\n')

>>> f.write('world\n')

#Close the file and flush the output buffer to disk
>>> f.close()

Read


# 'r'Is the default processing mode
>>> f = open('data.txt')

#Read the entire file
>>> bytes = f.read()
>>> bytes
'Hello\nworld\n'

#print interprets the meaning of control characters
>>> print bytes
Hello
world

#The contents of the file are always treated as strings
>>> bytes.split()
['Hello', 'world']

File related tools

Supported tools

--Pipe

Other types

Aggregate object

--Use a built-in function called set --A set object can correspond to "set operation" in mathematics.

>>> X = set('spam')

#Create two sets based on the sequence
>>> Y = set(['h', 'a', 'm'])
>>> X, Y
(set(['a', 'p', 's', 'm']), set(['a', 'h', 'm']))

#Crossing
>>> X & Y
set(['a', 'm'])

#Join
>>> X | Y
set(['a', 'p', 's', 'h', 'm'])

#difference
>>> X - Y
set(['p', 's'])

Fixed precision decimal or Boolean

#Fixed precision decimal
>>> import decimal
>>> d = decimal.Decimal('3.141')
>>> d + 1
Decimal("4.141")

#Boolean type
>>> 1 > 2, 1 < 2
(False, True)
>>> bool('spam')
True

# None
>>> X = None
>>> print X
None

#Create a list of 100 None
>>> L = [None] * 100
>>> L
[None, None, None, None, None, None, None, None, None, None, None, None, None,...List of 100 None...]

# Types
>>> type(L)
<type 'list'>

#The type itself is also an object
>>> type(type(L))
<type 'type'>

Type check

--In Python, it's usually best not to do type checking --When writing a program, you should pay attention to the interface of the object.

#Type check
>>> if type(L) == type([]):
print 'yes'
yes

#Check the name of the type
>>> if type(L) == list:
print 'yes'
yes

#"Object-oriented" confirmation method
>>> if isinstance(L, list):
print 'yes'
yes

User-created class

Worker class definition


class Worker:
  #Initialization
  def __init__(self, name, pay):
    #self corresponds to a new object
    self.name = name
    self.pay = pay
  def lastName(self):
    #Split string with whitespace
    return self.name.split()[-1]
  def giveRaise(self, percent):
    #Overwrite salary
    self.pay *= (1.0 + percent)
#Create two instances
>>> bob = Worker('Bob Smith', 50000)

#Both have name and pay
>>> sue = Worker('Sue Jones', 60000)

#Method call. bob becomes self
>>> bob.lastName()
'Smith'

#sue is self
>>> sue.lastName()
'Jones'

#Changed pay of sue
>>> sue.giveRaise(.10)
>>> sue.pay
66000.0

Summary

What are Python's built-in objects?

--Numerical value --Integer --Long integer --Floating --Decimal point --Fixed precision decimal --String --Normal string --Unicode string --List --Dictionary --Tuple

With built-in objects

--An object that is prepared in Python and is always available. --If you want to use an object other than the built-in object, you need to import the module and call the function in it.

What is immutability?

--The property that once an object is created, no changes can be made after that. --Numbers, strings, tuples, etc. can be classified as invariant objects --In the expression that operates the immutable object, the object is not changed (overwritten) as the execution result, and a new object is created.

What is a sequence

--One or more objects arranged in a certain order --Strings, lists, tuples, etc. are classified into sequences. --All objects belonging to the sequence support operations such as indexing, concatenation, and slicing. --Type-specific operations are also possible by using the methods of each type.

What is a map?

--A set of objects --The order in which the elements are arranged is not fixed --Each element has a "key" --Only dictionaries are classified as maps among the built-in objects.

What is polymorphism?

--Even if the code is the same, its meaning changes depending on the type of object to be processed. --In Python, the same code automatically changes its function depending on the target object --One code can handle many kinds of objects

Recommended Posts

Python built-in object
Python built-in object
Built-in python
Object oriented in python
Python built-in functions ~ Zip ~
About Python3 ... (Ellipsis object)
Wrap Python built-in functions
Python
String object methods in Python
[python] Value of function object (?)
Null object comparison in Python
Various Python built-in string operations
Python variables and object IDs
Prolog Object Orientation for Python Programmers
[Ubuntu] [Python] Object tracking using dlib
Touch a Python object from Elixir
python dict object memorandum (mysterious document)
Python basics ⑤
python + lottery 6
Python Summary
Python comprehension
Python technique
Studying python
Build an environment for Blender built-in Python
Python 2.7 Countdown
Python memorandum
Python FlowFishMaster
Python service
[Python] Attribute Error:'list' object has no attribute'replace'
python tips
python function ①
Python basics
Python memo
Conquer 69 Python built-in functions 6th p ~ r
ufo-> python (3)
Python comprehension
install python
Python Singleton
Python basics ④
Python Memorandum 2
python memo
Python Jinja2
Python increment
atCoder 173 Python
[Python] function
Python installation
python tips
Installing Python 3.4.3.
Try python
Python memo
Create a JSON object mapper in Python
Python iterative
Python algorithm
Python2 + word2vec
[Python] Variables
Python functions
Python sys.intern ()
Python tutorial
Python decimals
python underscore
Python summary