SoFunction
Updated on 2024-12-11

Python's list and tuple details

I. Python list (list)

1. Introduction to the sequence

The sequence isPythonThe most basic data structure in the Each element in a sequence is assigned a number - its position, or index, with the first index being 0 and the second index being

1, and so on.Python has six built-in types for sequences, but the most common are lists and tuples. The operations that are all possible with sequences include indexing, slicing, adding, multiplying, and checking members. In addition, thePythonMethods for determining the length of a sequence and for determining the largest and smallest elements are already built in.

Python:Variable and immutable sequences

Variable Sequence:Lists, collections, and dictionaries can be added, deleted, or changed without the sequence address page changing.

Immutable sequence:Tuples, strings No additions, deletions, or modifications.

# Variable sequences: lists, dictionaries, collections
list_1 = [10,20,30]
print(id(list_1))   The address of #list_1 is: 2927159489792
list_1.append(40)
print(id(list_1))   #list_1 has address: 2927159489792 Changed value, list address did not change

# Immutable sequences: strings, tuples
str_1 = "HelloWorld"
print(id(str_1))    #str_1 has address: 2244899454896
str_1 = str_1+"1"
print(id(str_1))    #str_1 address is: 2244900762928 Changed value and string address changed

2. Overview of the list

A list is an ordered sequence containing zero or more elements and is of type Sequence.

Features:

  • a. The length and content of the list is variable (you are free to add, delete or replace elements in the list).
  • b. The list has no length limit
  • c. Elements in lists can be of different types (either basic data types, lists, tuples, dictionaries, collections, and other custom types of objects)

3. Create a list

To create a list, simply enclose the different comma-separated data items in square brackets.As shown below:

#Creating a list way one
list_0 = []  #Empty list
list_1 = ['elephan','monkey','tiger']
list_2 = [1,2,3]
list_3 = [1,2.2,'tiger',True,list_1]   # Lists can store different data types

# Create a list of ways two: use list () built-in function list (obj) function will be a string, range () objects, tuples and other objects into a list.
list_4 = list("python")
list_5 = list([1,2,3,4,5])
list_6 = list((1,2,3))
list_7 = list(range(1,5,2))

4. List of indexes

# Index of the list
list_1 = [1,2.2,'tiger',True]
print(list_1[0])
print(list_1[3])
#print(list_1[4]) Error reported, exceeding the length of the list

5. Segmentation of the list

#Slicing of lists
list_1 = [1,2.2,'tiger',True]
print(list_1[1:3])
print(list_1[0:3:2])
print(list_1[-1:0:-1])    #When reverse slicing, note that the step size should be negative

6. Segmented assignment of lists

x = [1,2,3,4]
x[1] = 1    # Replace the index with a 1 in the lower corner
print(x)
x[2:] = 5,6 # Replacement from the index with the lower corner labeled 2
print(x)
x[1:1] = [1,2,3,4,5,6,7]    # Insert "1,2,3,4,5,6,7" at position 1 of the variable index.
print(x)

#Running results
[1, 1, 3, 4]
[1, 1, 5, 6]
[1, 1, 2, 3, 4, 5, 6, 7, 1, 5, 6]

7. Loop through the list

In order to efficiently output the data in the list one by one, you can use thewhilerespond in singingforloop to facilitate the output list.

The while loop traverses the list:

x = [1,2,3,4,5,6,7,8,9]
length = len(x)
i = 0
while i<length:
    print(x[i])
    i+=1


The for loop traverses the list:

x = [1,2,3,4,5,6,7,8,9]
for n in x:
    print(n)
 

8. Finding elements and counting

index(obj) method:Used to return the position of the first occurrence of the specified element in the list, or to throw an exception if the element is not in the list.

animal = ['elephant','monkey','snake','tiger',(1,2,3)]
print(((1,2,3))
print(("snake"))
#print(("Meow Meow")) #Exception thrown if Meow Meow is not found
x = input("Please enter the animal you are looking for.")
if x in animal:
    a = (x) # Returns the index value
    print('elemental{0}The index in the list is:{1}'.format(x,a))
else:
    print("The element does not exist in the list.")
 

The count(obj) method:Counts the number of times the specified element appears in the list

x = [1,2,2,2,3,4,[1,2,3,4],(1,2),(1,2)]
a = (2)
print(a)
b = ((1,2))
print(b)
#Running results
3
2

9. Add elements to the list

The list adds elements:append(obj)methodologiesextend(seq)methodologiesinsert(index,obj)methodologies

append(obj):Adding new elements, objects to the end of the list

add_list = [0,1,2,3,4]
add_list.append(5)  # Add an element at the end 5
print(add_list)
add_list.append([6,7])  # Add a list object at the end [6,7]
print(add_list)
x = [8,9]
add_list.append(x)  # Add a list object x at the end
print(add_list)
#Running results
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, [6, 7]]
[0, 1, 2, 3, 4, 5, [6, 7], [8, 9]]

 extend(seq):Append multiple values from another sequence at once to the end of the list (expanding the original list with a new one)

list_1 = [1,2,3]
list_2 = [4,5,6]
list_1.extend("python") #merge sequence python with list_1
print(list_1)
list_1.extend(list_2) # Consider list_2 as a sequence and merge this sequence with list_1
print(list_1)
 

insert(index,obj):You can add a specified object to a specified location

#insert() method
number = [1,2,4,5]
(2,3)  # Add element 3 at position indexed 2
print(number)
(5,[6,7])  # Add object [6,7] at index 5
print(number)
x = [8,9]
(6,x)  # Add object x at position indexed 6
print(number)
#Running results
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, [6, 7]]
[1, 2, 3, 4, 5, [6, 7], [8, 9]]
 

10. List delete elements

The list deletes elements:delcommandpop()methodologiesremove()methodologies

del command:Remove elements from the list according to index (remove one or more)

number = [1,2,3,4,5,6,7,8,9]
del number[2]   # Delete the element with index 2
print(number)
del number[1:3] # Slicing removes elements at index 1:3
print(number)
del number[-1:0:-2] # slice to remove elements at indexes -1:0:-2
print(number)

The pop([obj]) method:Used to remove an element from a list (defaults to last) and returns the value of that element (removes one)

number = [1,2,3,4,5,6,7,8,9]
print(())  # Deletes the last element by default and returns the value of that element
print(number)
print((0) )  # Delete the element with index 0
print(number)
 

 remove(obj) method: removes the first match of a value in the list.

# Use the remove method to remove all 'abc' from list x.
x = ["123",'abc',"ABC",'python','abc']
while 'abc' in x:
    ('abc')
print(x)
#Running results
['123', 'ABC', 'python']

11. List Sorting

reverse() method: Used to store the elements of a list in reverse (modifying the original list values).

x = [1,2,3,4]
()
print(x)
#Running results
[4, 3, 2, 1]
 

sort([key = None], [reverse = False]) method:Used to sort the original list (the default is ascending), the new list will overwrite the original list after sorting

key:Passed to the key parameter is a function that specifies each element of the iterable object to be sorted by the function

reverse: Indicates whether to sort in reverse order, default is False.

# Here is a first look at the sort() function without the key parameter, you can easily know the result
li = [[1, 7], [1, 5], [2, 4], [1, 1]]
()
print(li)  
# [[1, 1], [1, 5], [1, 7], [2, 4]] Sort by 0 dimensions by default and then by 1 dimension.

def fun(li):
    return li[1]
# This is where you pass the function fun to the parameter key to get the result #
(key=fun)
print(li) # [[1, 1], [2, 4], [1, 5], [1, 7]]     
# is the second number of each child element in li to sort by

# No-parameter sorting
x = [1,2,3,4,5]
()
print(x)
#Specify parameters to sort, length, reverse
x_1 = ['a','abc','abcd','ab']
x_1.sort(key=len,reverse=True)
print(x_1)

#Running results
[1, 2, 3, 4, 5]
['abcd', 'abc', 'ab', 'a']

sorted(iterable,[key = None],[reverse = False]) function:Sorting is the same assortSame, butsortedfunction returns a new list, leaving the original list unaltered.

iterable:Represents an iterable object, in this case the list name.

# No-parameter sorting
x_1 = [1,5,2,3,4]
x_2 = sorted(x_1)
print(x_1)
print(x_2)

# Specify the parameter ordering
x_1 = ['a','abc','abcd','ab']
x_2 = sorted(x_1,key=len,reverse=True)
print(x_1)
print(x_2)

#Running results
[1, 5, 2, 3, 4]
[1, 2, 3, 4, 5]
['a', 'abc', 'abcd', 'ab']
['abcd', 'abc', 'ab', 'a']

Second, Python tuples (tuple)

Tuples are immutable sequences, so add, delete and change operations cannot be used.

1. Why tuples should be designed as immutable sequences

  • Simultaneous operation of objects without locking in a multitasking environment
  • Try to use immutable sequences in your program

Attention:Stored in tuples are references to objects

  • If the object stored in the tuple is itself immutable, it cannot reference other objects
  • If the object stored in the tuple is itself a mutable object, the reference to the mutable object cannot be changed, but the data can be

tuple_1 = (10,[20,30],"string")
print("1",tuple_1[0],type(tuple_1[0]),id(tuple_1[0]))
print("2",tuple_1[1],type(tuple_1[1]),id(tuple_1[1]))
print("3",tuple_1[2],type(tuple_1[2]),id(tuple_1[2]))
#tuple_1[0] = 1
#tuple_1[1] = 1 These three lines of code report an error and cannot modify the value of the tuple
#tuple_1[2] = 1
tuple_1[1].insert(2,40)  # Use the list method to change the value of the list, but the reference address of the list does not change
print("4",tuple_1[1],type(tuple_1[1]),id(tuple_1[1]))

Run results:

1 10 <class 'int'> 2698032015952
2 [20, 30] <class 'list'> 2698040063232
3 string <class 'str'> 2698040230832
4 [20, 30, 40] <class 'list'> 2698040063232

2. Create tuple

# Way 1: Create directly using ()
tuple_1 = (1,2.2,"Python",True)
print(tuple_1)          #Run the result (1, 2.2, 'Python', True)
#() can be omitted.
tuple_1 = 1,2.22,"Python",True
print(tuple_1)          #Run the result (1, 2.22, 'Python', True)

# Way two: use the built-in function tuple (obj) function will be strings, range () objects, tuples and other objects into tuples
tuple_2 = tuple("python")
tuple_3 = tuple([1,2,3,4,5])
tuple_4 = tuple((1,2,3))
tuple_5 = tuple(range(1,5,2))
tuple_6 = tuple({"a":"Zhang San",True:1})
print(tuple_2)      #Run the results ('p', 'y', 't', 'h', 'o', 'n')
print(tuple_3)      #Running results (1, 2, 3, 4, 5)
print(tuple_4)      #Running results (1, 2, 3)
print(tuple_5)      #Running results (1, 3)
print(tuple_6)      #Run the result ('a', True)

# Note: When the value of a tuple, contains only one element, be sure to add a comma
tuple_7 = (1,)
tuple_8 = (1)
tuple_9 = ("You.",)
tuple_10 = ("You.")
print(tuple_7)      #Running results (1,)
print(tuple_8)      #Running result 1
print(tuple_9)      #Run the results ('you',)
print(tuple_10)     # Run the results you
 

3. Iteration of tuples

tuple_1 = ('python','world',94)
# Method 1: Use a loop to utilize the index and get all the elements of the tuple
i = 0
length = len(tuple_1)
while i<length:
    print(tuple_1[i])
    i += 1
# Method II
for x in tuple_1:
    print(x)

4. Built-in functions for tuples

Three functions that sequences will all have: len()   max()  min()
tuple(): function:Take a sequence as a parameter and convert it to a tuple, or return the parameter as is if the parameter itself is a tuple (refer to Knowledge Point 2 on tuples above, Creating Tuples)

Up to this point this article onPythonThe list and tuple details of the article is introduced here, more relevantPythonFor list and tuple content please search my previous posts or continue to browse the related posts below I hope you will support me in the future!