Table of contents
3. Python Containers (Containers)
4. Common operations on tuples
e. Check whether the element exists in the tuple
I. Introduction
Python is a high-level programming language created by Guido van Rossum in 1991. It is known for its concise, easy-to-read syntax, powerful functionality, and wide range of applications. Python has a rich standard library and third-party libraries that can be used to develop various types of applications, including web development, data analysis, artificial intelligence, scientific computing, automation scripts, etc.
Python itself is a great general-purpose programming language and, with the help of some popular libraries (numpy, scipy, matplotlib), becomes a powerful environment for scientific computing. This series will introduce the Python programming language and methods of using Python for scientific computing, mainly including the following content:
- Python: basic data types, containers (lists, tuples, sets, dictionaries), functions, classes
- Numpy: arrays, array indexing, data types, array math, broadcasting
- Matplotlib: plots, subplots, images
- IPython: Creating notebooks, typical workflow
2. Experimental environment
Python 3.7
Run the following command to check the Python version
python --version
3. Python Containers (Containers)
0. Introduction to containers
Containers in Python are objects used to store and organize data. Common containers include List, Tuple, Set and Dictionary.
- Lists are ordered mutable containers that can contain elements of different types and are created using square brackets ([]).
my_list = [1, 2, 3, 'a', 'b', 'c']
- Tuples are ordered immutable containers that can also contain elements of different types and are created using parentheses (()).
my_tuple = (1, 2, 3, 'a', 'b', 'c')
- A set is an unordered and non-duplicate container used to store unique elements. It is created using curly brackets ({}) or the set() function.
my_set = {1, 2, 3, 'a', 'b', 'c'}
- A dictionary is an unordered container of key-value pairs used to store values with unique keys. It is created using curly braces ({}) or the dict() function.
my_dict = {'name': 'Alice', 'age': 25, 'city': 'New York'}
These containers provide different methods and operations for storing, accessing and processing data. You can choose a suitable container type according to your specific needs.
1. List
2. Tuple
A tuple (tuple) is a sequence type in Python, similar to a list, which can store multiple elements. Unlike lists, tuples are immutable and cannot be modified once created .
1. Initialization
a. Use parentheses ()
my_tuple = ()
A tuple created this way is empty and contains no elements.
Create tuples using parentheses () and comma-separated elements:
my_tuple = (1, 2, 3)
b. Omit parentheses
my_tuple = 1, 2, 3
Comma-separated elements are combined into a tuple. The parentheses are omitted, but still a tuple.
c. tuple()
function
tuple()
Functions can convert other iterable objects (such as lists, strings, dictionaries, etc.) into tuples.
- Convert list to tuple:
my_list = [1, 2, 3, 4, 5]
my_tuple = tuple(my_list)
print(my_tuple) # 输出:(1, 2, 3, 4, 5)
- Convert string to tuple:
my_string = "Hello, World!"
my_tuple = tuple(my_string)
print(my_tuple) # 输出:('H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!')
- Convert dictionary to tuple:
my_dict = {'a': 1, 'b': 2, 'c': 3}
my_tuple = tuple(my_dict)
print(my_tuple) # 输出:('a', 'b', 'c')
2. Access tuple elements
a. Index
# 使用索引访问元组中的特定元素
print(my_tuple[0]) # 输出:a
print(my_tuple[-1]) # 输出:d
b. slice
# 使用切片操作获取元组的子序列
print(my_tuple[1:3]) # 输出:('b', 'c')
print(my_tuple[1:]) # 输出:('b', 'c', 'd')
print(my_tuple[:]) # 输出:('a', 'b', 'c', 'd')
print(my_tuple[1:-1]) # 输出:('b',)
print(my_tuple[:-1]) # 输出:('a', 'b', 'c')
3. Characteristics of tuples
a. Immutable
Tuples are immutable; once created, the elements of a tuple cannot be modified. Elements in a tuple cannot be added, deleted, or modified.
my_tuple = (1, 2, 3)
my_tuple[0] = 4 # 会引发一个类型错误(TypeError: 'tuple' object does not support item assignment)
b. Contains different types
Tuples can contain elements of different types, such as integers, strings, floating point numbers, etc.
my_tuple = (1, "hello", 3.14)
c. Nestable
Tuples can be nested, that is, tuples can contain other tuples as elements.
# 访问元组中的元素
element1 = nested_tuple[0]
print(element1) # 输出: (1, 'hello')
print(nested_tuple[2][0]) # 输出: world
4. Common operations on tuples
a. Tuple length
b. Element count
c. Tuple concatenation
d. Tuple repetition
e. Check whether the element exists in the tuple
my_tuple = (1, 2, 3)
# 获取元组的长度
print(len(my_tuple)) # 输出:3
# 元素计数
print(my_tuple.count(2)) # 输出: 1(元素2在元组中出现的次数)
# 元组拼接
new_tuple = my_tuple + (4, 5)
print(new_tuple) # 输出:(1, 2, 3, 4, 5)
# 元组重复
repeated_tuple = my_tuple * 2
print(repeated_tuple) # 输出:(1, 2, 3, 1, 2, 3)
# 检查元素是否存在于元组中
print(2 in my_tuple) # 输出:True
print(4 not in my_tuple) # 输出:True
5. Unpacking
Tuple unpacking (Tuple destructuring, Tuple Unpacking) is a method of assigning the elements of a tuple to multiple variables. Through tuple destructuring, the values in the tuple can be easily assigned to the corresponding variables.
my_tuple = (1, 2, 3)
a, b, c = my_tuple
print(a) # 输出:1
print(b) # 输出:2
print(c) # 输出:3
In this example, the tuple my_tuple
contains three elements, 1, 2, and 3. Through tuple destructuring, we assign these three values to variables a
, b
and c
. The result is that the variable a
has a value of 1, the variable b
has a value of 2, and the variable c
has a value of 3.
It should be noted that the number of variables must be the same as the number of elements in the tuple, otherwise an exception will be thrown.
- The number of variables is less than the number of elements in the tuple:
my_tuple = (1, 2, 3)
a, b = my_tuple
ValueError: too many values to unpack (expected 2)
- There are more variables than elements in the tuple:
my_tuple = (1, 2, 3)
a, b, c, d = my_tuple
ValueError: not enough values to unpack (expected 4, got 3)
6. Traverse
a. for loop
my_tuple = (1, 2, 3, 4, 5)
for element in my_tuple:
print(element)
b. enumerate()
function
my_tuple = (1, 2, 3, 4, 5)
for index, element in enumerate(my_tuple):
print(f"Index: {index}, Element: {element}")