Home Backend Development Python Tutorial Detailed explanation of Python's built-in data structures

Detailed explanation of Python's built-in data structures

Apr 27, 2018 pm 03:36 PM
python data structure Detailed explanation

This article summarizes and introduces 5 built-in data structures in Python and operation examples. It is very detailed. Friends who need it can refer to it.

1. List

list is a data structure in which a series of items can be stored. The items of the list need to be separated by commas and enclosed in a pair of square brackets to indicate that this is a list. The following example is used to show some basic operations of list:

# 定义一个 list 对象 class_list:
class_list = ['Michael', 'Bob', 'Tracy']
# 获得一个 class_list 的长度
print 'class have', len(class_list), 'students'
# 访问class_list中的对象
print 'The 3rd student in class is', class_list[2]
# 往 class_list 中插入对象
class_list.append('Paul')
# 从 class_list 中删除一个项目
del class_list[0]
# 对 class_list 进行排序
class_list.sort()
# 遍历整个class_list中的项目
print 'These students are :',
for student in class_list:
  print student,
Copy after login

The output result is:

class has 3 students
The 3rd student in class is Tracy
These students are: Bob Paul Tracy

There are a few things to note about the above code:

You can add any type of object to the class_list, that is to say, it is not required to be in a list Items are of the same type. You can even insert a list into class_list.
The sorting function acts on itself rather than returning a copy, which is different from the string type because strings cannot be modified.
The end keyword parameter of the print function is used to specify the output after the input is completed. The default is a newline character. The above code uses a space character to replace the newline character.

2. Tuple

tuple is not much different from list in usage and concept. Tuple can be regarded as a Read-only version of the list. This means that once a tuple is defined, it cannot be modified - objects cannot be added or deleted, nor can objects in the tuple be modified.

The items in the tuple should also be separated by commas, and the items should be enclosed in parentheses to indicate that they are a tuple. This parentheses are optional, which means that a tuple can be defined in the following two ways:

t = 'Adam', 'Lisa', 'Bart'
t = ('Adam', 'Lisa', 'Bart')
But omitting the pair of parentheses is not necessarily a good habit. In addition, when the tuple has only one item, there must be a comma after the first item. In this case, t = ('Adam',) should be defined like this. This may seem like an odd constraint, but without the comma, the tuple defined without parentheses becomes t = 'Adam', which is obviously ambiguous.

3. Dictionary

A dictionary can be viewed as a collection of key-value pairs. Keys must be unique, and each key is associated with a value. The key must be an immutable object (such as tuple, numeric type, string). Also note that the key-value pairs in the dictionary are not ordered in any way.

The definition of a dictionary should be in the format d={key1 : value1, key2 : value2, key3 : value3}. Keys and values ​​are separated by colons, key-value pairs are separated by commas, and all key-value pairs are enclosed in braces. Some basic operations are as follows:

# 字典的定义
d = {
  'Adam': 95,
  'Lisa': 85,
  'Bart': 59
}
# 通过键来获取值
print "Adam's score is", d['Adam']
# 删除一个键值对
del d['Bart']
# 遍历字典
for name, score in d.items():
  print '{0} is {1}'.format(name, score)
# 往字典中增加一个键值对
d['Paul'] = 72
# 判断字典中是否存在某键,也可以用 if ab.has_key('Lisa')
if 'Lisa' in d:
  print "Lisa's address is", d['Lisa']
Copy after login

The output result is:

Adam's score is 95
Lisa is 85
Adam is 95
Lisa's address is 85
Copy after login

4. Sequences

The three types introduced above The built-in data structures are all sequences, and the index operation is a basic operation of the sequence. The objects in the sequence can be accessed directly through the subscript operation. Although the subscripting operation has been demonstrated above - queues and tuples are subscripted with numbers, and dictionaries are subscripted with keywords.

The subscript of the sequence starts from 0. In the above example, only the subscript is a positive number. In fact, the subscript can also be a negative number, such as -1,-2,-3... Negative subscripts represent positions in the opposite direction. For example, class_list[-1] returns the last item in class_list.

The sequence not only supports negative subscripts but also double subscripts. This pair of double subscripts represents an interval. For example, class_list[0:3] returns a copy of the subsequence from subscript 1 to subscript 3 in class_list. Note that this interval is a pair of half-closed and half-open intervals. This operation is called a slicing operation. If the second index of the slicing operation exceeds the range of the sequence, the slicing operation will terminate at the end of the sequence. Both subscripts in the slicing operation have default values. The default value of the first is 0, and the size of the second is the length of the sequence.

You can also provide a third parameter for the slicing operation. The third parameter represents the step size of the slicing operation. Its default value is 1. The step size represents the distance between items, such as name[0:10:3]. What is returned is the subsequence composed of subscripts 0, 3, 6, and 9 in name.

5. Set

A collection is an unordered collection of simple objects. Sets are suitable when you only care about whether an object exists in a collection, regardless of the order in which it exists or the number of times it appears. Basic functions: determine whether it is a member of a set, whether a set is a subset of another set, obtain the intersection of two sets, etc. Example:

s = set(['Adam', 'Lisa', 'Bart', 'Paul'])
# 判断对象是否在集合中
if 'Bart' in s:
  print "Bart is in ?", 'Bart' in s
# 使用copy函数来拷贝一个set
sc = s.copy()
# 往集合中添加对象
sc.add('Bill')
# 从集合中删除对象
sc.remove('Adam')
# 求两个集合的交集,也可以使用 s.intersection(sc)
print s & sc
Copy after login

Output result:

Bart is in ? True
set(['Lisa', 'Paul', 'Bart'])
Copy after login

Related recommendations:

Comprehensive analysis of the scope of variables in Python starting from local variables and global variables

The above is the detailed content of Detailed explanation of Python's built-in data structures. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles