[Python] basic data structure: list - tuple - dictionary - set

1. Brief introduction

Python provides a variety of built-in data structures, including lists ( List), tuples ( Tuple), and dictionaries ( Dictionary). These data structures are widely used in Python programming, but they each have their own characteristics and applicable scenarios.

  • A list is an ordered collection in which elements can be added and removed at any time. Lists are mutable, that is, you can modify the list's elements and size. The elements of a list can be of any type, including numbers, strings, booleans, and even other lists. Lists are often used to store ordered collections of elements, such as a column of numbers or a set of names.

  • Tuples are very similar to lists, but tuples are immutable, that is, you cannot modify the elements and size of the tuple. This makes tuples safer than lists, because you can be sure that the elements of the tuple will not be changed while the program is running. Tuples are often used to store data sets that should not be changed, such as a date or the latitude and longitude of a geographic location.

  • A dictionary is an unordered collection that stores key-value pairs. The keys of a dictionary must be unique, while the values ​​can be of any type. Dictionaries are mutable, that is, you can add, remove, and modify the key-value pairs of the dictionary. Dictionaries are often used to store and look up key-value pairs, such as a phone book or a word count. (hash table)

  • A set is an unordered, non-repeating collection of elements. Basic functionality includes relationship testing and elimination of duplicate elements. Collection objects also support mathematical operations such as union (union), intersection (intersection), difference (difference) and symmetric difference (symmetrical difference set) .

Compared

  • Both lists and tuples are ordered collections, the main difference between them is that lists are mutable while tuples are immutable . This means that if you need a collection where elements can be added, removed, and modified at any time, you should use a list; if you need a collection that cannot be changed once created, you should use a tuple.

  • The main difference between dictionaries and lists and tuples is that dictionaries are unordered and store key-value pairs rather than individual elements. This makes dictionaries useful when working with data that requires key-value pairs, such as when looking up elements, which are often faster than lists and tuples.

  • The main difference between sets and lists, tuples, and dictionaries is that sets are unordered , non-repeating sets of elements. This makes collections useful when uniqueness of elements is required and collection operations, such as when looking up an element, are usually faster than lists.
    insert image description here

2. List details in Python

A list (List) in Python is a commonly used data structure that can store a series of ordered elements. Lists are mutable, which means you can add, remove, or change their elements after you create them. The elements in a list can be of any type, including numbers, strings, booleans, and even other lists.

2.1 Create list

Creating a list is as simple as enclosing elements []in square brackets and ,separating them with commas. For example:

my_list = [1, 2, 3, 'apple', 'banana', True]

In the example above, my_listthat's a list of three integers, two strings, and a boolean.

2.2 Accessing List Elements

You can access elements in a list by index. In Python, indexing starts at 0. For example, to access the first element in the list above, you would do:

first_item = my_list[0]  # first_item 现在是 1

You can also use negative indices to access elements from the end of the list. For example, my_list[-1]will return the last element in the list.

2.3 Modify list elements

Since lists are mutable, you can modify elements in the list by index. For example:

my_list[0] = 'orange'  # my_list 现在是 ['orange', 2, 3, 'apple', 'banana', True]

2.4 List slicing

Slicing is a way to get a subset of a list. You can get a new list by specifying the start index and end index. For example:

sub_list = my_list[1:4]  # sub_list 现在是 [2, 3, 'apple']

Note that slicing is left-closed-right, that is, the new list returned contains the element at the start index, but not the end index.

2.5 List methods

Python's list provides many methods, such as append(), insert(), remove(), pop(), and sort()so on. These methods allow you to manipulate lists more conveniently.

For example, append()a method could add a new element to the end of the list:

my_list.append('grape')  # my_list 现在是 ['orange', 2, 3, 'apple', 'banana', True, 'grape']

remove()method to delete specific elements in the list:

my_list.remove('banana')  # my_list 现在是 ['orange', 2, 3, 'apple', True, 'grape']

2.6 List comprehensions

List comprehensions are a concise way of creating lists in Python. It can generate a new list with one line of code. For example, the following code generates a list of squares from 1 to 10:

squares = [x**2 for x in range(1, 11)]  # squares 是 [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

3. Detailed explanation of tuples in Python

Tuple in Python is a commonly used data structure that can store a series of ordered elements. Tuples are very similar to lists, but with one key difference: tuples are immutable, which means you cannot add, remove, or change their elements after they are created. Elements in a tuple can be of any type, including numbers, strings, booleans, or even other tuples or lists.

3.1 Create tuples

Creating a tuple is as simple as enclosing the elements ()in parentheses and ,separating them with commas. For example:

my_tuple = (1, 2, 3, 'apple', 'banana', True)

In the above example, my_tupleit is a tuple containing three integers, two strings, and a boolean.

Note that if you are creating a tuple with only one element, you need to add a comma after the element, eg my_tuple = (1,).

3.2 Accessing tuple elements

You can access elements in a tuple by index. In Python, indexing starts at 0. For example, to access the first element in the tuple above, you could do:

first_item = my_tuple[0]  # first_item 现在是 1

You can also use negative indices to access elements from the end of the tuple. For example, my_tuple[-1]will return the last element in the tuple.

3.3 Tuples are immutable

Once a tuple is created, you cannot change its elements or size. This means that you cannot add, remove or modify elements of a tuple like a list. Python will raise an error if you try to do this.

my_tuple[0] = 'orange'  # 这将引发错误

Although tuples themselves are immutable, if the elements in the tuple are mutable (like a list), then you can modify those elements.

3.4 Tuple Slicing

Slicing is a way to get a subset of tuples. You can get a new tuple by specifying the start index and end index. For example:

sub_tuple = my_tuple[1:4]  # sub_tuple 现在是 (2, 3, 'apple')

Note that slices are left-closed-right, that is, the new tuple returned contains the element at the start index, but not the end index.

3.5 Tuple methods

Since tuples are immutable, they have fewer methods than lists. Python's tuple only provides two methods: count()and index(). count()method is used to count the number of specific elements in the tuple and index()method is used to find the index of the first occurrence of a specific element in the tuple.

my_tuple = (1, 2, 3, 2, 2, 4)
count = my_tuple.count(2)  # count 现在是 3
index = my_tuple.index(2)  # index 现在是 1

4. Detailed explanation of dictionaries in Python

A dictionary in Python is a very important data structure that stores key-value pairs. Dictionaries are mutable, which means you can add, remove, or change their key-value pairs after the dictionary is created. The keys and values ​​of a dictionary can be of any type, including numbers, strings, booleans, or even other dictionaries or lists.

4.1 Create a dictionary

Creating a dictionary is as simple as enclosing key-value pairs {}in braces and ,separating them with commas. The key and value in each key-value pair are :separated by a colon. For example:

my_dict = {
    
    'name': 'Alice', 'age': 20, 'is_student': True}

In the above example, my_dictit is a dictionary containing three key-value pairs.

4.2 Accessing dictionary elements

You can access the values ​​in the dictionary by key. For example, to access the value corresponding to the 'name' key in the dictionary above, you could do:

name = my_dict['name']  # name 现在是 'Alice'

Python will throw if you try to access a key that doesn't exist in the dictionary KeyError. To avoid this kind of error, you can use get()methods to access the values ​​in the dictionary, and if the key does not exist, get()the method will return Noneor the default value you specify.

city = my_dict.get('city', 'New York')  # city 现在是 'New York'

4.3 Modify dictionary elements

You can modify the values ​​in the dictionary by key. For example:

my_dict['age'] = 21  # my_dict 现在是 {'name': 'Alice', 'age': 21, 'is_student': True}

You can also use update()methods to update multiple key-value pairs in a dictionary at once.

my_dict.update({
    
    'age': 22, 'city': 'London'})  # my_dict 现在是 {'name': 'Alice', 'age': 22, 'is_student': True, 'city': 'London'}

4.4 Dictionary methods

Python's dictionary provides many methods, such as keys(), values(), items(), pop(), and clear()so on. These methods allow you to manipulate dictionaries more conveniently.

For example, keys()a method can return all keys in a dictionary, values()a method can return all values ​​in a dictionary, and items()a method can return all key-value pairs in a dictionary:

keys = my_dict.keys()  # keys 现在是 dict_keys(['name', 'age', 'is_student', 'city'])
values = my_dict.values()  # values 现在是 dict_values(['Alice', 22, True, 'London'])
items = my_dict.items()  # items 现在是 dict_items([('name', 'Alice'), ('age', 22), ('is_student', True), ('city', 'London')])

pop()The method can delete and return the value of a specific key in the dictionary, and clear()the method can empty the dictionary:

age = my_dict.pop('age')  # age 现在是 22,my_dict 现在是 {'name': 'Alice', 'is_student': True, 'city': 'London'}
my_dict.clear()  # my_dict 现在是 {}

5. Detailed explanation of collections in Python

A set (Set) in Python is a unique data structure that provides an efficient way to handle data uniqueness and set operations. A collection is an unordered, non-repeating set of elements, which means that the elements in the collection are unique and insertion order is not guaranteed.

5.1 Create a collection

Creating a collection is as simple as enclosing the elements {}in curly braces and ,separating them with commas. For example:

my_set = {
    
    1, 2, 3, 'apple', 'banana', True}

In the above example, my_setit is a set containing three integers, two strings and a boolean.

Note that if you want to create an empty collection, you need to use set()a function, not empty curly braces, because empty curly braces {}represent an empty dictionary in Python.

empty_set = set()  # 创建一个空集合

5.2 Basic operations on collections

Collections provide a series of basic operations, including adding elements, removing elements, and checking whether an element exists.

my_set = {
    
    1, 2, 3}

my_set.add(4)  # my_set 现在是 {1, 2, 3, 4}
my_set.remove(1)  # my_set 现在是 {2, 3, 4}
print(2 in my_set)  # 输出 True

5.3 Mathematical operations on sets

Sets support some common mathematical operations, such as union, intersection, difference, and symmetric difference.

set1 = {
    
    1, 2, 3, 4}
set2 = {
    
    3, 4, 5, 6}

print(set1.union(set2))  # 输出 {1, 2, 3, 4, 5, 6}
print(set1.intersection(set2))  # 输出 {3, 4}
print(set1.difference(set2))  # 输出 {1, 2}
print(set1.symmetric_difference(set2))  # 输出 {1, 2, 5, 6}

5.4 Applications of Sets

Since the elements in a set are unique, sets are often used to remove duplicate elements in lists.

my_list = [1, 2, 2, 3, 3, 3]
my_set = set(my_list)  # my_set 现在是 {1, 2, 3}

Sets are also often used in membership tests, since finding an element in a set is usually faster than looking up an element in a list.

my_set = {
    
    1, 2, 3, 4, 5}
print(3 in my_set)  # 输出 True


Write love you forever into the end of the poem ~

Guess you like

Origin blog.csdn.net/weixin_43764974/article/details/132134270