Detailed explanation of Python built-in functions / methods - list

Detailed explanation of Python built-in functions / methods - list

A list is an ordered and changeable collection and is the most commonly used Python data type. In Python, lists are written using square brackets [].

1. Create list

In Python, the data types of elements in the list can be different, including integers, floating-point numbers, complex numbers, etc. of course, they can also include lists, tuples, dictionaries, collections, etc.

1.1 create a list using []

To create a list, you only need to enclose different data items separated by commas with square brackets [].

  • Create an empty list
list0 = []
  • Create a non empty list
list1 = ['Baidu', 'Alibaba', 'Tencent']

1.2 use the list() function to convert to a list

In Python, we can use the list() function to convert strings, tuples, dictionaries, collections and other similar objects into lists. See the following built-in functions for specific usage:

2. Access list

Like lists, we can use subscript indexes to access an element in a tuple (get the value of an element) or slices to access a group of elements in a tuple (get a child tuple).

2.1 subscript index access

Subscript index access tuples are divided into two categories: forward index and reverse index, with the format of list_name[i], where, list_name refers to the list name, I refers to the index value, and I can be positive (positive index) or negative (negative index).

As you can see, list_name[0] represents the first element of the list, list_name[-1] represents the last element of the list.

list_name = ['wzq', 'lgl', 'gz', 'whl', 'sj', 'hxw']
print(list_name[0])
print(list_name[-1])
wzq
hxw

Forward index: from the first (subscript 0), the second (subscript 1)

Reverse index: from the penultimate (subscript -1), penultimate (subscript -2)

2.2 slice access

If you don't understand the above description, please refer to the following table:

Tuple valuewzqlglgzwhlsjhxw
Forward index012345
Reverse index-6-5-4-3-2-1

The format of using slice to access the list is list_ Name[strat: end: step], where start represents the start index, end represents the end index, and step represents the step size.

list_name = ['wzq', 'lgl', 'gz', 'whl', 'sj', 'hxw']
print(list_name[1:5:2])
print(list_name[-6:-1:3])
['lgl', 'whl']
['wzq', 'whl']

When using slices to access list elements, list_ Name[strat: end: step], [start:end] is the left closed and right open interval, that is, the element represented by end cannot be accessed.

2.3 for loop traversal list

You can use the for loop to traverse the items in the list:

fruit_list = ['apple', 'pear', 'cherry']
for i in fruit_list:
    print(i)
apple
pear
cherry

2.4 check whether the item exists

To determine whether the specified item exists in the list, we can use the in keyword:

# Check whether 'apple' exists in the list
fruit_list = ['apple', 'pear', 'cherry']
print('apple' in fruit_list)
True

When using the in keyword to check whether the specified item exists in the list, if it exists, it returns True; Otherwise, it returns False.

2.5 changing list values

After we create a list, we can modify or update the data items in the list. Of course, we can also use the append() method to add list items.

fruit_list = ['apple', 'pear', 'cherry']
fruit_list[2] = 'banana'
print(fruit_list)
['apple', 'pear', 'banana']

Note: once a tuple is created, its value cannot be changed, but there are other solutions.

2.6 list connection (Consolidation) / copy

Like strings, the + and * signs can be used between lists to connect and copy tuples, which means that they can generate a new list.

1. + connect (merge)

x = [1, 2, 3]
y = [4, 5, 6]
print(x + y)
[1, 2, 3, 4, 5, 6]

2. * replication

x = ['Hello']
print(x * 5)
['Hello', 'Hello', 'Hello', 'Hello', 'Hello']

2.7 nested list

Using nested lists creates other lists within the list.

x = [1, 2, 3]
y = ['a', 'b', 'c']
z = [x, y]
print(z)
[[1, 2, 3], ['a', 'b', 'c']]

2.8 list comparison

List comparison requires the introduction of the eq method of the operator module.

# Import operator module
import operator

a = [1, 2]
b = [2, 3]
c = [2, 3]
print("operator.eq(a, b):", operator.eq(a, b))
print("operator.eq(b, c):", operator.eq(b, c))
operator.eq(a, b): False
operator.eq(b, c): True

3. Built in function

3.1 print()

1. print() function

We are already familiar with the function of print(), which is printout.

my_list = ['pink', True, 1.78, 65]
print(my_list)
['pink', True, 1.78, 65]

3.2 determine the list item len()

2. len() function

When we want to determine how many items (elements) there are in a list, we can use the len() function.

fruit_list = ['apple', 'banana', 'cherry']
print(len(fruit_list))
3

3.3 return variable type()

3. type() function

Use the type() function to determine what type a variable is (string, list, tuple, dictionary, or collection).

info_list = ['name', 'gender', 'age', 'height', 'weight']
print(type(info_list))
<class 'list'>

When it comes to info_ When list uses type() to determine the type of variable, it will return <class'list'>, indicating that this is a list.

3.4 convert to list()

4. tuple() function

The function of tuple() is to convert other types to tuple types. The detailed usage is as follows:

  • Convert string to list
str1 = 'Hello Python'
print(list(str1))
['H', 'e', 'l', 'l', 'o', ' ', 'P', 'y', 't', 'h', 'o', 'n']
  • Convert tuples to lists
tuple1 = ('Hello', 'Python')
print(list(tuple1))
['Hello', 'Python']
  • Convert dictionary to list
dict1 = {'Hello': 'Python', 'name': 'pink'}
print(list(dict1))
['Hello', 'name']
  • Convert a set to a list
set1 = {'Hello', 'Python', 'name', 'pink'}
print(list(set1))
['Python', 'name', 'pink', 'Hello']
  • Convert interval to list
range1 = range(1, 6)
print(list(range1))
[1, 2, 3, 4, 5]

3.5 tuple element max(), min()

5. max() function and min() function

The max() function returns the maximum value of the element in the list. The min() function returns the minimum value of the element in the list.

list1 = [4, 6, 2, 0, -5]
print(max(list1))
print(min(list1))

list2 = ['a', 'z', 'A', 'Z']
print(max(list2))
print(min(list2))
6
-5
z
A

3.6 del delete list

  • Delete a single element

We can use del list_name[i] to delete a specified element, where list_name refers to the list name, and I refers to the index value of the specified value.

list_de = ['Baidu', 'Alibaba', 'Tencent', 'Bytedance']
del list_de[1]
print(list_de)
['Baidu', 'Tencent', 'Bytedance']
  • Delete list

del function can not only delete an element, but also delete the whole list.

list_de = ['Baidu', 'Alibaba', 'Tencent', 'Bytedance']
del list_de

When we use the del function to delete a list, and then use the print() function to print out, an error nameerror: name'List will be reported_ De'is not defined, indicating that the list is not defined.

4. Built in method

4.1 add elements append(), insert(), extend()

1. append() method

The append() method is used to add a new object at the end of the list.

grammar

list.append(element)

Parameter value

parameterdescribe
elementRequired. Elements of any type (string, number, object, etc.).

example

  • Add element
fruit_list = ['apple', 'banana', 'cherry']
fruit_list.append('pear')
print(fruit_list)
['apple', 'banana', 'cherry', 'pear']
  • Add list
x = [1, 2, 3]
y = ['A', 'B', 'C']
x.append(y)
print(x)
[1, 2, 3, ['A', 'B', 'C']]

2. insert() method

The insert() method is used to insert the specified object into the specified position of the list.

grammar

list.insert(position, element)

Parameter value

parameterdescribe
positionRequired. Number specifying where to insert the value.
elementRequired. Element, any type (string, number, object, etc.).

example

  • Insert the value "orange" as the second element into the fruits list:
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
print(fruits)
['apple', 'orange', 'banana', 'cherry']
  • Insert list y into list x
x = [1, 2, 3]
y = ['a', 'c']
x.insert(0, y)
print(x)
[['a', 'c'], 1, 2, 3]

append() can only add elements or lists at the end, and insert() can add elements or lists anywhere.

3. extend() method

The extend() method is used to append multiple values in another sequence at the end of the list at one time (expand the original list with the new list).

grammar

list.extend(iterable)

Parameter value

parameterdescribe
iterableRequired. Any iteratable object (list, set, tuple, etc.).

example

aver = ['A', 'B', 'C']
  • Add a string element to the end of the list
str1 = 'Hello'
aver.extend(str1)
print(aver)
['A', 'B', 'C', 'H', 'e', 'l', 'l', 'o']
  • Add list elements to the end of the list
list1 = [1, 2, 3]
aver.extend(list1)
print(aver)
['A', 'B', 'C', 1, 2, 3]
  • Add tuple elements to the end of the list
tuple1 = (1, 2, 3)
aver.extend(tuple1)
print(aver)
['A', 'B', 'C', 1, 2, 3]
  • Add dictionary elements to the end of the list
dict1 = {'name': 'pink', 'gender': True}
aver.extend(dict1)
print(aver)
['A', 'B', 'C', 'name', 'gender']
  • Add collection elements to the end of the list
set1 = {1, 2, 3}
aver.extend(set1)
print(aver)
['A', 'B', 'C', 1, 2, 3]
  • Add interval to the end of the list
range1 = range(1,10)
aver.extend(range1)
print(aver)
['A', 'B', 'C', 1, 2, 3, 4, 5, 6, 7, 8, 9]

4.2 number of element occurrences count()

The count() method is used to count the number of times an element appears in the list.

grammar

list.count(value)

Parameter value

parameterdescribe
valueRequired. Any type (string, number, list, tuple, etc.). The value to search.

example

num = [1, 4, 2, 9, 7, 8, 9, 3, 1]
print(num.count(9))
2

4.3 specified value index()

The index() method is used to find the index position of the first match of a value from the list.

grammar

list.index(element)

Parameter value

parameterdescribe
elementRequired. Any type (string, number, list, etc.). The value to search.

example

num = [4, 55, 64, 32, 16, 32]
print(num.index(32))
3

When the searched value appears multiple times in the list, only the first position is returned.

4.4 sort the list ()

The sort() method is used to sort the original list. If parameters are specified, the comparison function specified by the comparison function is used.

grammar

list.sort(reverse=True|False, key=myFunc)

Parameter value

parameterdescribe
reverseOptional. reverse=True will sort the list in descending order. The default is reverse=False.
keyOptional. A function that specifies the sort criteria.

example

  • Sort the list alphabetically:
words = ['Name', 'Gender', 'Age', 'Height', 'Weight']
words.sort()
print(words)
['Age', 'Gender', 'Height', 'Name', 'Weight']
  • Sort the list in descending order:
words = ['Name', 'Gender', 'Age', 'Height', 'Weight']
words.sort(reverse=True)
print(words)
['Weight', 'Name', 'Height', 'Gender', 'Age']
  • Sort the list by the length of the value:
# Function that returns the length of the value:
def myfunc(e):
    return len(e)

words = ['a', 'bb', 'ccc', 'dddd', '']

words.sort(key=myfunc)
print(words)
['', 'a', 'bb', 'ccc', 'dddd']
  • Sort the dictionary list according to the "year" value of the dictionary:
# Function that returns the value of'year ':
def myfunc(e):
    return e['year']

words = [
    {'char': 'a', 'year': 1963},
    {'char': 'b', 'year': 2010},
    {'char': 'c', 'year': 2019}
]

words.sort(key=myfunc)
print(words)

[{'char': 'a', 'year': 1963}, {'char': 'b', 'year': 2010}, {'char': 'c', 'year': 2019}]
  • Sort the list in descending order by the length of the value:
# Function that returns the length of the value:
def myfunc(e):
    return len(e)

words = ['aa', 'b', 'ccc', 'dddd']

words.sort(reverse=True, key=myfunc)
print(words)
['dddd', 'ccc', 'aa', 'b']
  • Specify the sorting of elements in the list to output the list:
# Get the second element of the list
def takeSecond(elem):
    return elem[1]

# list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]

# Specify the second element sort
random.sort(key=takeSecond)

# Output category
print('Sort list:', random)
Sort list: [(4, 1), (2, 2), (1, 3), (3, 4)]

4.5 copy list ()

The copy() method is used to copy the list, similar to a[:].

grammar

list.copy()

Parameter value

No parameters

example

fruits = ['apple', 'banana', 'cherry', 'orange']
x = fruits.copy()
print(x)
['apple', 'banana', 'cherry', 'orange']

4.6 reverse the list order ()

The reverse() method is used to reverse the elements in the list.

grammar

list.reverse()

Parameter value

No parameters

example

fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits)
['cherry', 'banana', 'apple']

4.7 delete elements pop(), remove(), clear()

1. pop() method

The pop() method is used to remove an element in the list (the last element by default) and return the value of this element.

grammar

list.pop(pos)

Parameter value

parameterdescribe
posOptional. Number, specifying the position of the element to be deleted. The default value is -1, which returns the last item.

example

  • When pos is not specified, the last element is deleted by default
fruits = ['apple', 'banana', 'cherry']
fruits.pop()
print(fruits)
['apple', 'banana']
  • pos specifies the location of the element to be deleted
fruits = ['apple', 'banana', 'cherry']
fruits.pop(1)
print(fruits)
['apple', 'cherry']

2. remove() method

The remove() method is used to remove the first match of a value in the list.

grammar

list.remove(element)

Parameter value

parameterdescribe
elementRequired. Elements of any type (string, number, list, etc.) to be deleted.

example

num = [1, 3, 2, 8, 3]
num.remove(3)
print(num)
[1, 2, 8, 3]

When there are multiple deleted elements in the list, the first one will be deleted by default.

3. clear() method

The clear() method is used to clear the list, similar to del a[:].

grammar

list.clear()

Parameter value

No parameters

example

word = ['A', 'B', 'C']
word.clear()
print(word)
[]

The function of the clear() method is to clear the list. When printf() is used to print it after execution, it will output [], indicating that the list still exists, but it is only an empty list.

The del function is used to delete a list. When printf() is used to print it after execution, an error nameerror: name'word'is not defined. will be reported.

5. Summary

functiondescribe
print()Printout
len()Identify list items
type()Return variable type
list()Convert to list
max()Returns the maximum value of a list element
min()Returns the minimum value of a list element
delDelete list
methoddescribe
append(obj)Add a new object at the end of the list
insert(index, obj)Add an element at the specified location
extend(seq)Adds a list element (or any iteratible element) to the end of the current list
count(obj)Count the number of times an element appears in the list
index(obj)Returns the index of the first element with the specified value
sort( key=None, reverse=False)Sort the original list
copy()Copy list
reverse()Reverse the order of the list
pop([-1])Remove an element in the list (the last element by default) and return the value of the element
remove(obj)Remove the first match of a value in the list
clear()clear list

The above is the whole content of this article! If it helps you, please praise it! Collect it! Welcome to comment!!!

Last edited on: 2022/7/27 20:42

Tags: Algorithm Python Back-end Pycharm programming language

Posted by tomms on Fri, 05 Aug 2022 22:22:02 +0530