Introduction to Python quick programming # learning notes 05# | Chapter 5: combined data types (list, tuple, set and Dictionary)

What is an iteratable object?

Objects that support isomorphic for... in... Statements to obtain data iteratively are iteratable objects.

String, list, collection, dictionary, and file type data are all iteratable objects.

Use the isinstance() function to determine whether the target is an iteratable object. The example code is as follows:

from import Iterable

ls = [3,4,5]
print(isinstance(ls, Iterable))

The run result is True

1, Understanding composite data types

What is a composite data type?

We know that combination means to organize data together. The data types we have learned before are integer, floating point and string data types.

Combined data types refer to organizing multiple data of the same type or different types into a whole. According to different data organization methods, Python combined data types are divided into three types: sequence type, set type and mapping type.

  • Sequence type
classificationData sequenceexplain
Sequence typeString (str), list (list), and tuple (tuple)The sequence type supports two-way index, forward increment index and reverse decrement index.
  • Collection type

Set has three characteristics: certainty, heterogeneity and disorder.

Certainty: given a set, whether any element is in the set is determined.
Dissimilarity: the elements in the collection are different from each other.
Disorder: the elements in the set have no order (sets with different order but the same elements can be regarded as the same set)

  • mapping type

The mapping type stores elements in the form of key value pairs, and there is a mapping relationship between keys and values in key value pairs.

Dictionary is the only built-in mapping type in Python. The keys of the dictionary must comply with the following two principles:

First, each key can only correspond to one value, and the same key is not allowed to appear repeatedly in the dictionary;
Second, the keys in the dictionary are immutable types.

2, List

2.1 create list

Python lists are created in two ways:

The first one can be directly created with "[]" brackets;
The second can be created with the built-in function list().


list1 = []
list2 = ['p', 'y', 't', 'h', 'o', 'n']
list3 = list()
list4 = list('python')   # Element 'python'

Note: when using list() to create a list, an error will be reported if the incoming data is not an iteratable type!

list3 = list(1)  # 1 is not an iteratable object

Error: TypeError:'int' object is not iterable

2.2 accessing list elements

The function of the list is to store multiple data at one time. Programmers can operate on these data: add, delete, modify and query

Lookup of list elements

Find (access) with subscript of list element

Format: sequence name [subscript]

The subscript is the address and number assigned to each element of the list in the computer memory.

name_list = ['Tom', 'Lily', 'Rose']

print(name_list[0]) # Tome
print(name_list[1]) # Lily

Find (access) with function


2.3 adding list elements (append, extend and insert)

Adds the specified data to the list

Function 1: append() append data at the end of the function list

Syntax: list name. Append (data)


num = ['1' , '2', '3']
num.append('9')  # String sequence
num.append([11, 22])  # List sequence

# Result 1: ['1', '2', '3', '9']
# Result 2: ['1', '2', '3', '9', [11, 22]]

Summary of append() function:
1. List data is modifiable -- lists are variable types
2. When the append() function appends data, if the data is a sequence, the entire sequence is appended to the end of the list.

Function 2: append data at the end of the function list

Syntax: list name. Extend (data)


name_list = ['Tom', 'Lily', 'Rose']

name_list.extend('xiaoming')  # Breaks up a string data sequence and appends a single element to the end of the list
name_list.extend(['xiaoming', 'xiaoming']) # Disassemble the list and append it to the end of the list

# Result 1: ['Tom', 'Lily', 'Rose', 'x', 'I', 'a', 'o','m ',' I ',' n ',' g ']
# Result 2: ['Tom', 'Lily', 'Rose', 'xiaoming', 'xiaoming']

extend() function summary
1. When the data appended by the extend() function is a sequence, the data in the data sequence is disassembled into a single element and appended to the end of the list one by one

Function 2: append data at the end of the insert function list

Syntax: list name. Insert (position subscript, data)


name_list = ['Tom', 'Lily', 'Rose']

name_list.insert(1, 'xiaoming')  # Insert 'xiaoming' into the list where the subscript is 1

# Result 1: ['Tom', 'xiaoming', 'Lily', 'Rose',]

Summary of insert() function
1. The insert() function adds data at the specified location

2.4 element sorting (sort, reverse)

Inverse: reverse() function

Only the position of the elements in the list changes, and they are not sorted according to the size of the elements!!!

# reverse()

list1 = [1, 4, 2, 3, 9]

# Results: [9,3,2,4,1]

Sorting: sor() function

Syntax: list name. sort(key = None, reverse = False)

(the parameter key is used to sort the values of dictionary data series)


# sort() sort: ascending and descending
list1 = [1, 4, 2, 3, 9]
list1.sort()  # Default ascending order
list1.sort(reverse = False)  # Ascending order
list1.sort(reverse = True)  # Descending order
# Result 1: [1,2,3,4,9]
# Result 2: [1,2,3,4,9]
# Result 3: [9,4,3,2,1]

Note: reverse indicates the collation. reverse = True in descending order (3, 2, 1), reverse = False (default) in ascending order (1, 2, 3)

2.5 delete list elements (del, pop, remove and clear)

del() function

Function: delete the whole target (can be list or function) and delete the data of the subscript of the specified list

Syntax: del list name and del (list name)


name_list = ['tom', 'lily', 'rose']
name_list2 = ['tom', 'lily', 'rose']

del name_list
# del(name_list)
# Result: an error is reported. NameError 'name_list' is not defined because the list is not deleted

# del can delete the data of the specified subscript
del name_list2[0]
# Result: ['lily ',' Rose ']
print(name_list2) # 

pop() function

Function: delete the data of the specified subscript (the last data by default) and return the data.

Syntax: list name. Pop (subscript)


name_list = ['tom', 'lily', 'rose']

del_name = name_list.pop(1)  # Delete the element 'lily' with sequence subscript 1 and return 'lily'
# The result is: lily
# The result is: ['Tom ',' Rose ']

remove() function

Function: remove() function deletes the first match of an element in the list.

Syntax: List naming. Remove (data)


name_list = ['tom', 'lily', 'rose']

# Result: ['Tom ',' Lily ']

clear() function

Function: clear list

Syntax: List naming. clear()


name_list = ['tom', 'lily', 'rose']

# Result: [] empty list

2.6 list derivation

List derivation (function: simplify code; create or control regular lists)

# Requirements: 0, 1, 2, 4,... (create regular list)
# 1. Cycle realization
# 2. List derivation (function: simplify code; create or control regular list)

# Method 1: while implementation
list1 = []
i = 0 
while i < 10:
	i += 1

# Mode 2: for implementation

list2 = []

for i in range(10)

# Mode 3: List derivation

list3 = [i for i in range(10)] 

List derivation with if

# Requirement: list of 0-10 even data [0,2,4,6,8]
# 1. Simple list derived range step size
list1 = [i for i in range(0,10,2)]

# 2.for loop plus if to create regular list
list2 = []
for i in range(10)
	if i % 2 == 0:

# 3. Rewrite the for loop with the if code to the list derivation with if
list3 = [i for i range(10) if i % 2 ==0]

Multiple for loops implement list derivation

Requirements: create the following list

[(1, 0), (1, 1), (1, 2),(2, 0), (2, 1), (2, 2)]

# Requirements: [(1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
# analysis:
# Data 1:1 and 2 -- range (1,3)
# Data 2:0 1 2 -- range (3)

# Method 1: for nesting
list2 = []
for i in range(1, 3):
	for j in range(3):
		list2.append((i, j))

# Method 2: multiple for implementations list derivation
list1 = [(i, j) for i in range(1, 3) for j in range(3)]

3, Tuple

3.1 application scenarios of tuples

Thinking: if you want to store multiple data, but these data cannot be modified, how do you operate?
A: list? A list can store multiple data at once, but the data in the list can be changed.

num = [10, 20 ,30]
num[0] = 100  # Change the element subscript 0 in the list from 10 to 100

Note: a tuple can store multiple data, and the data in the tuple cannot be modified.

3.2 definition of tuple

Definition: tuples are defined in parentheses, and each data is separated by commas. The data can be of different data types (it is best to ensure that the data types in tuples are consistent).

t1 = (10, 'a', 1.2) # For multiple data type tuples, it is best to ensure that the data types in the tuples are consistent!
t2 = (10,) # Single data tuple

t3 = ()    # Empty tuple

Note: if the defined tuple has only one data, the comma "," after the element cannot be omitted, otherwise the data type is the data type of the data of the only element in parentheses.

t2 = (10,) # tuple
t3 = (10) # integer 
t4 = ('hello') # character string

Common operations of tuples

Tuples can also be created by using the built-in function tuple(). When the function parameter list is empty, the function creates tuples, and when the parameter is an iteratable object, the function creates non empty tuples.

Sample code

t1 = tuple()   	 # Create empty tuple
t2 = tuple([1,2,3])  # Create tuples from lists
t3 = tuple('python') # Create tuples ('p ',' y ','t', 'H', 'o', 'n') from strings
t4 = tuple(range(5))   # Create tuples with iteratable objects (0,1,2,3,4)

print(t1, t2,t3,t4)

Like the list, Python supports accessing elements of tuples through indexes and slices, and traversing element groups in a loop. The example code is as follows:

t1 = tuple()   	 # Create empty tuple
t2 = tuple([1,2,3])  # Create tuples from lists
t3 = tuple('python') # Create tuples ('p ',' y ','t', 'H', 'o', 'n') from strings
t4 = tuple(range(5))   # Create tuples with iteratable objects (0,1,2,3,4)
print(t2[1])    # Access tuple elements by index
print(t3[3:5])   # Group elements in a sliced way
for data in t3:
	print(data, end='')

The output results are as follows:

Case training

1. Top ten singers

2. Magic cube array

4, Assemble

4.1 creating collections

Create a collection using {} or set(), but if you want to create an empty collection, you can only use set(), because {} is used to create a dictionary.

# 1. Create a collection with data
s1 = {10, 20, 30, 40, 50}  # Set has no subscript, set has no order
s2 = {10, 10,20, 30, 40, 50}  # The element data in the collection cannot be repeated (to reprint the data)
print(s2) # duplicate removal

# 2. Create an empty collection

s3 = {}   # Note: {} represents a dictionary
print(s3) # Dictionary type

s5 = set('abcdefg')
# Result: the element data in the {e ',' B ',' a ','d', 'C', 'f', 'g'} set is out of order

s4 = set() 
print(type(s4)) # set 

4.2 common operations of collection - adding data (add and update)

s1 = {10, 20}
#1. A set is a variable data sequence
# add()

# Results: {100, 10, 20}

# The collection has the function of de duplication. If the additional data is the existing data of the collection, nothing will be done
# Results: {100, 10, 20}

# update(): the added data is a sequence
s1.update([10,20,30,40]) # Set s1 append list

4.3 common operations of collection delete data (remove, dicard and pop)

The remove() function deletes the specified data in the collection. If the data does not exist, an error is reported.

s1 = {10, 20}

s1.remove(10) # report errors

The discard() function deletes the specified data in the collection. If the data does not exist, no error will be reported.

s1 = {10, 20}


pop() function randomly deletes a data summarized in the collection and returns this data.

s1 = {10, 20, 30, 40, 50}
del_num = s1.pop()

4.4 common operations of collection - find data

In: judge whether the data is in the set sequence
not in: judge that the data is no longer a collection sequence

s1 = {10, 20, 30, 40, 50}

print(10 in s1) # Return True
print(10 not in s1) # Return False

5, Dictionary

5.1 create dictionary

Dictionary features:

  • The symbol is brace {}
  • The data is in the form of key value pairs
  • Key value pairs are separated by commas

Sample program:

(create a dictionary with data and an empty dictionary)

# Create a dictionary with data
dict1 = {'name':'Tom', 'age':'18', 12:'male'}

# Create an empty dictionary
dict2 = {}   # Method 1
dict3 = dict() # Method 2
# dict3 = dict({'name':'Tom', 'age':'18', 'sexy':'male'}) # Method 2


Output results:

5.2 dictionary access (key value, get, keys, values and items)

Dictionary lookup (access)

Method 1: key value search

Note: if the current key exists, put back the value corresponding to the key; Otherwise, an error is reported

# Dictionary lookup (access)
# Note: if the current key exists, put back the value corresponding to the key; Otherwise, an error is reported

# Method 1: key value search
dict1 = {'name': 'Tom', 'age': '18', 12:'male'}

Method 2: function search

  • get()
    Python provides a built-in method get(), which obtains the corresponding value from the dictionary according to the key. If the specified key does not exist, it returns the default value (default). The syntax format is as follows:
    Dictionary name. Get (key [, default])
# Method 2: find with get() function
dict1 = {'name': 'Tom', 'age': '18', 12:'male'}

Python dictionary data is divided into keys, values and elements (key value pairs). In addition to direct access by keys, python also provides built-in methods key(), values(), items() for accessing all keys, values and elements in the dictionary. The example code of these functions is as follows:

key() - get all keys in the dictionary
values() - get all values in the dictionary
items() - get all the elements in the dictionary

dict1 = {'name': 'Tom', 'age': '18', 12:'male'}
print(dict1.keys())  # Use the keys() method to get all the keys
print(dict1.values())  # Use the values() method to get all the values
print(dict1.items())   # Use the items() method to get all the elements

The output results are as follows:

5.3 addition and modification of dictionary elements ('key = value 'and update)

Addition of dictionary elements:

Method 1: Dictionary variable name ['key'] = value

Method 2: Dictionary variable name. Update (key name = value)

# Method 1. Dictionary variable name ['key'] = value
# dict1 = {'name': 'Tom', 'age': '18', 12:'male'}
# dict1['sco'] = 100                                  # Add element
# print(dict1)

# Method 2: Dictionary variable name. Update (key name = value)
dict1 = {'name': 'Tom', 'age': '18', 12:'male'}
dict1.update(sexy = 'male')                          # Add element

Modification of dictionary elements:

The essence of modifying dictionary elements is to obtain values through keys, and then re assign values to the elements. The operation of modifying an element is similar to that of adding an element. The example code is as follows:

stu_dict = {'stu1': 'LAN LAN','stu2':'Honghong','stu3': 'Huang Huang'}
stu_dict.update(stu3 = 'Xiao Hei')									# Modify the element through update()
stu_dict['stu2'] = 'Xiao Ming'										# Modify element values by specifying keys

Run the code and the results are as follows:

5.4 deletion of dictionary elements (pop, popitem and clear)

Python supports modifying elements in the dictionary through the pop(), popitem(), and clear() functions

pop() method

Function: pop() method can delete the corresponding element in the dictionary according to the specified key. If the deletion is successful, this method returns the value of the target element

stu_dict = {'stu1': 'LAN LAN','stu2':'Honghong','stu3': 'Huang Huang'}

Run the program, and the output results are as follows:

popitem() method

Function: use this method to randomly delete elements in the dictionary. In fact, popitem() can delete elements randomly because dictionary elements are disordered and there is no distinction between "first item" and "last item". If the deletion is successful, the deleted coarse element is returned.

stu_dict = {'stu1': 'LAN LAN', 'stu2': 'Honghong', 'stu3': 'Huang Huang'}

Run the program, and the output results are as follows:

clear() method

Function: clear() is used to clear the elements in the dictionary

stu_dict = {'stu1': 'LAN LAN', 'stu2': 'Honghong', 'stu3': 'Huang Huang'}

The results are as follows:

5.5 dictionary derivation

The format and usage of the dictionary derivation are similar to those of the list derivation, except that the dictionary derivation is surrounded by braces "{}" and contains two parts of keys and values. The specific format is as follows:

{ new_key : new_value for key , value in dict.items()}

The dictionary derivation can be used to quickly exchange the positions of keys and values in the dictionary. The example code is as follows:

old_stu_dict = {'stu1': 'LAN LAN', 'stu2': 'Honghong', 'stu3': 'Huang Huang'}
new_stu_dict = {value : key for key, value in old_stu_dict.items()}

Run the program, and the output results are as follows:

Case training

1. Youth has you

2. Mobile phone address book

Combining data types and operators

Public operation and data sequence all support the operation mode.

Three aspects: operators, public methods and container type conversion

  • operator
operatordescribeSupported container types
+mergeString, list, tuple
*copyString, list, tuple
inDoes the element existString, list, tuple, dictionary
not inDoes the element not existString, list, tuple, dictionary


str1 = 'aa'
str2 = 'bb'

list1 = [1, 2]
list2 = [10, 20]

t1 = (1, 2)
t2 = (10, 20)

dict1 = {'name':'pyton'}
dict2 = {'age':'18'}

print(str1 + str2) # The result was aabb
print(list1 + list2) # The printout result is: [1,2,10,20]
print(t1 + t2)
# print(dict1 + dict2)  # Error: the dictionary does not support merge operation


str1 = 'a'
list1 = ['hello']
t1 = ('world',)

# *: copy
print(str1 * 5)
# Print 10 '-'
print('-' * 10)
print(list1 * 5)  # The output result is: ['hello', 'hello', 'hello', 'hello']
print(t1 * 5)

Does the element exist

dict1 = {'name':'pyton','age':'19'}

print('name' in dict1)
print('name' not in dict1)
print('name' in dict1.keys)
print('name' not in dict1.keys)
print('name' in dict1.values)

Tags: Python Back-end

Posted on Tue, 09 Nov 2021 17:07:28 -0500 by amy_ewe