Python Sequence Operation Guide: Basic usage and operations of lists, strings, and tuples

sequence

Sequence is the most basic data structure in Python, which is used to save a set of ordered data. All data has a unique position (index) in the sequence, and the data in the sequence are assigned indices in the order they are added. Sequences in Python include lists, strings, tuples and other types.

list

A list is one of the most commonly used data types in Python. It is a mutable ordered sequence whose elements can be accessed by index. Here are some common operations:

Create list

Lists can be created using square brackets []and can contain elements of any type.

my_list = [1, 2, "hello", 3.5, True]
print(my_list)  # 输出:[1, 2, 'hello', 3.5, True]

access element

Elements in the list can be accessed by index, which starts at 0, indicating the first element.

my_list = [1, 2, "hello", 3.5, True]

# 访问第一个元素
print(my_list[0])  # 输出:1

# 访问倒数第一个元素
print(my_list[-1])  # 输出:True

Modify element

The elements in the list can be modified by indexing.

my_list = [1, 2, "hello", 3.5, True]

# 修改第三个元素
my_list[2] = "world"
print(my_list)  # 输出:[1, 2, 'world', 3.5, True]

Add and remove elements

You can use append()the method to add an element to the end of the list, insert()the method to insert an element at a specified position, and pop()the method to delete an element at a specified position.

my_list = [1, 2, "hello", 3.5, True]

# 添加元素
my_list.append("how are you")
print(my_list)  # 输出:[1, 2, 'hello', 3.5, True, 'how are you']

# 在指定位置插入元素
my_list.insert(2, "Python")
print(my_list)  # 输出:[1, 2, 'Python', 'hello', 3.5, True, 'how are you']

# 删除指定位置的元素
my_list.pop(2)
print(my_list)  # 输出:[1, 2, 'hello', 3.5, True, 'how are you']

range()

The range() function is used to generate a sequence of natural numbers, as follows:

The range() function can be called with three parameters, namely the starting position, the ending position and the step size. The specific instructions are as follows:

  1. If only one argument is provided, i.e. range(stop), then the default starting position is 0 and the step size is 1, generating a stop-1sequence of natural numbers from 0 to .

    r = range(5)  # 生成序列[0, 1, 2, 3, 4]
    
  2. If two arguments are supplied, i.e. , then a sequence of natural numbers from to range(start, stop)is generated , with the step size defaulting to 1.startstop-1

    r = range(0, 10)  # 生成序列[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
  3. If three arguments are supplied, i.e. range(start, stop, step), then a sequence of natural numbers from startto is generated stop-1with step size step.

    r = range(0, 10, 2)  # 生成序列[0, 2, 4, 6, 8]
    r = range(10, 0, -1)  # 生成序列[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
    

It should be noted that the range() function returns a range object rather than directly returning a list. If you need to convert the range object into a list, you can use the list() function to convert, such as list(range(5)).

The range() function can conveniently perform a specified number of iteration operations in a for loop, and can achieve similar effects more concisely.

string

A string is an immutable sequence type that represents an object composed of a sequence of characters. Here are some common operations:

Create string

Strings can be created using single quotes ' 'or double quotes " ".

my_string = "hello world"
print(my_string)  # 输出:hello world

access characters

Characters in a string can be accessed by index, which starts at 0, indicating the first character.

my_string = "hello world"

# 访问第一个字符
print(my_string[0])  # 输出:h

# 访问倒数第一个字符
print(my_string[-1])  # 输出:d

String slice

You can use the slicing operation to obtain a substring within a specified range. The syntax is [起始索引:结束索引]: Does not contain the character at the ending index.

my_string = "hello world"

# 获取前5个字符
print(my_string[:5])  # 输出:hello

# 获取从第6个字符开始到最后的子字符串
print(my_string[6:])  # 输出:world

Modify string

Since string is an immutable type, the characters in it cannot be modified directly. If you need to modify the string, you can use string slicing and addition operations to achieve this.

my_string = "hello world"

# 修改第一个字符
my_string = "H" + my_string[1:]
print(my_string)  # 输出:Hello world

tuple

A tuple is an immutable sequence type that represents an object composed of a sequence of elements. Unlike lists, elements of tuples cannot be changed.
Here are some common operations:

Create tuple

Tuples can be ()created using parentheses and can contain elements of any type.

my_tuple = (1, 2, "hello", 3.5, True)
print(my_tuple)  # 输出:(1, 2, 'hello', 3.5, True)

access element

Elements in a tuple can be accessed by index, which starts at 0, indicating the first element.

my_tuple = (1, 2, "hello", 3.5, True)

# 访问第一个元素
print(my_tuple[0])  # 输出:1

# 访问倒数第一个元素
print(my_tuple[-1])  # 输出:True

Get the number of elements

You can use len()the method to get the number of elements in a tuple.

my_tuple = (1, 2, "hello", 3.5, True)

# 获取元素数量
print(len(my_tuple))  # 输出:5

Characteristics of tuples:

  1. Tuples ()are created using parentheses and can be an empty tuple or a tuple containing multiple elements.

    empty_tuple = ()
    my_tuple = (1, 2, 3, 4, 5)
    
  2. The elements in the tuple can be of any data type and are separated by commas ,.

    my_tuple = (10, 'hello', True, [1, 2, 3])
    
  3. Tuples are immutable, meaning that once created, the elements of the tuple cannot be modified. Attempting to modify an element of a tuple raises TypeErroran error.

    my_tuple[0] = 100  # 报错:TypeError: 'tuple' object does not support item assignment
    
  4. Elements in a tuple can be accessed using indexes, which start from 0. Slicing can also be used to obtain subsets of tuples.

    print(my_tuple[0])     # 输出:10
    print(my_tuple[1:3])   # 输出:('hello', True)
    
  5. Tuples support unpacking (or destructuring), which allows each element of the tuple to be assigned to a variable.

    a, b, c, d = my_tuple
    print(a)  # 输出:10
    print(b)  # 输出:'hello'
    
  6. If you are not sure about the length of a tuple, you can use *to get the remaining elements.

    a, *b = my_tuple
    print(a)  # 输出:10
    print(b)  # 输出:['hello', True, [1, 2, 3]]
    

Tuples are useful in the following situations:

  • When you want your data to be immutable, you can use tuples as containers.
  • When returning multiple values ​​in a function, you can use tuples to return multiple values ​​concisely.

Note that tuples are immutable objects, so elements cannot be added, removed, or modified from a tuple. If you need to modify the data while manipulating it, you should use the list type.

mutable object

Three pieces of data are saved in each object:

  • id (identification)
  • type
  • value

For a list, it is a mutable object. Let's say we have a list a = [1, 2, 3].

Now let's do something:

Change the value of an object

We can modify the value of an object through variables, for example a[0] = 10. This operation does not change the object pointed to by the variable, but only modifies the value of the object.

Please note the following:

  • When we modify an object, if other variables also point to the object, the modification will also be reflected in other variables.
  • Modifying the value of an object does not change the variable itself.

Change the pointer of a variable

In addition to changing the value of an object, we can also reassign a variable to change the object it points to. For example, execution a = [4, 5, 6].

Please note the following:

  • Reassigning a value to a variable changes the object pointed to by the variable.
  • When reassigning a variable, it will not affect other variables.

To sum up, the variable is actually modified only when assigning a value to the variable, while other operations modify the object.

Here is a code example to help understand the above concepts:

a = [1, 2, 3]
b = a

print(a)  # 输出:[1, 2, 3]
print(b)  # 输出:[1, 2, 3]

a[0] = 10

print(a)  # 输出:[10, 2, 3]
print(b)  # 输出:[10, 2, 3]

a = [4, 5, 6]

print(a)  # 输出:[4, 5, 6]
print(b)  # 输出:[10, 2, 3]

comparison operator

In Python, we have several comparison operators that can be used to compare the value and identity of two objects:

  • ==: Compares the values ​​of two objects for equality.
  • !=: Compares whether the values ​​of two objects are not equal.
  • is: Compares whether the identities of two objects are equal, that is, whether they point to the same object.
  • is not: Compares whether the identities of two objects are not equal.

Consider the following code:

a = [1, 2, 3]
b = [1, 2, 3]

print(a, b)
print(id(a), id(b))
print(a == b)  # 输出:True,a和b的值相等
print(a is b)  # 输出:False,a和b不是同一个对象

In this example, we create two lists aand b, their values ​​are equal, but they are not the same object. So, using ==the operator will return True, and using isthe operator will return False.

Summarize

This blog post covers several sequence-related topics.

First, we introduced different types of sequences, including lists, strings, and tuples. We discussed how to create and access them, and provided methods for modifying elements, adding and removing elements. Next, we introduced the range() function, which can conveniently generate a sequence of natural numbers for loop and iterative operations.

In discussing strings, we learned how to create strings, access individual characters, and use slicing to obtain substrings. In addition, we pointed out that strings are immutable objects and cannot be modified directly, but modifications can be achieved by creating new strings.

When discussing tuples, we explained how to create tuples, access elements, and get the length of a tuple. At the same time, we emphasize that tuples are immutable objects and cannot be modified once created. We also covered how to change the value of an object and the operations that change the variables pointed to.

Overall, this blog post provides basic knowledge and operations about sequences, range() function, strings and tuples. These are important in programming for processing data, iterating through loops, and manipulating different types of sequences.

Hopefully this blog post will help you gain a clearer understanding of sequences and related operations.

Recommended Python boutique columns


Basic knowledge of python (0 basic entry)

[Basic knowledge of python] 0.print() function
[Basic knowledge of python] 1. Data types, data applications, data conversion
[Basic knowledge of python] 2. If conditional judgment and condition nesting
[Basic knowledge of python] 3.input() Functions
[Basic knowledge of python] 4. Lists and dictionaries
[Basic knowledge of python] 5. For loops and while loops
[Basic knowledge of python] 6. Boolean values ​​and four types of statements (break, continue, pass, else)
[Basic knowledge of python] 7. Practical operation - Use Python to implement the "Word PK" game (1)
[Python basic knowledge] 7. Practical operation - Use Python to implement the "Word PK" game (2)
[Python basic knowledge] 8. Programming thinking: how to Solving problems - Thinking Chapter
[Basic Knowledge of Python] 9. Definition and calling of functions
[Basic Knowledge of Python] 10. Writing programs with functions - Practical Chapter
[Basic Knowledge of Python] 10. Using Python to implement the rock-paper-scissors game - Function Practice Operation Chapter
[Python Basics] 11. How to debug - Common error reasons and troubleshooting ideas - Thinking Chapter
[Python Basics] 12. Classes and Objects (1)
[Python Basics] 12. Classes and Objects (2)
[Python Basics] Knowledge] 13. Classes and objects (3)
[Basic knowledge of python] 13. Classes and objects (4)
[Basic knowledge of python] 14. Building a library management system (practical operation of classes and objects)
[Basic knowledge of python] 15. Coding basic knowledge
[Python Basics] 16. File reading and writing basics and operations
[Python Basics] 16. Python implementation of "Ancient Poetry Writing Questions" (file reading, writing and coding - practical articles)
[Python Basics] 17. The concept of modules and How to introduce
[python basics] 18. Practical operation - use python to automatically send mass emails
[python basics] 19. Product thinking and the use of flow charts - thinking
[python basics] 20. Python implementation of "what to eat for lunch" ( Product Thinking - Practical Operation)
[Python Basics] 21. The correct way to open efficiently and lazy - Graduation
[python file processing] CSV file reading, processing, writing
[python file processing] Excel automatic processing (using openpyxl)
[python file processing] - excel format processing


python crawler knowledge

[python crawler] 1. Basic knowledge of crawlers
[python crawler] 2. Basic knowledge of web pages
[python crawler] 3. First experience of crawlers (BeautifulSoup analysis)
[python crawlers] 4. Practical crawler operations (crawling dishes)
[python crawlers] 5 .Practical crawler operation (crawling lyrics)
[python crawler] 6. Practical crawler operation (requesting data with parameters)
[python crawler] 7. Where is the crawled data stored?
[python crawler] 8. Learning from the past
[python crawler] 9. Log in with cookies (cookies)
[python crawler] 10. Command the browser to work automatically (selenium)
[python crawler] 11. Let the crawler report to you on time
[python crawler] 12. Build your crawler army
[python crawler] 13. What to eat will not get fat (practical crawler practice)
[python crawler] 14. Scrapy framework explanation
[python crawler] 15. Scrapy framework combat (popular job crawling Take)
[python crawler] 16. Summary and review of crawler knowledge points

Guess you like

Origin blog.csdn.net/qq_41308872/article/details/132760894