
Lists are one of the most commonly used data structures in Python. Mastering various operations on lists is crucial for Python programming. This article will comprehensively introduce 50 list operations in Python, covering creation, modification, access, sorting, and more.
Previous Python readings>>
15 Python Libraries for Automated Financial Data Retrieval
Automating Excel Operations with Python
30 Methods for Automated Office Image Processing in Python
30 Common Functions for Data Analysis with Python Pandas
25 Practical Automation Scripts in Python, Ready to Use
Quickly Develop a Web File Server with Python
Parsing and Converting JSON Format with Python
15 Automation Scripts for Processing Excel Data with Python
Batch Automation for Adding Watermarks to Images with Python
Automating PDF Operations with Python
10 Examples of Data Visualization Automation with Python (Including Code), Highly Recommended
30 Efficient Automation Scripts for Processing Financial Excel Data with Python
15 Efficient and Practical Automation Libraries in Python
Automating Word Operations with Python
Efficiently Handle 40 Tasks in One Line of Python Code
15 Common Scripts in Python
Functional Programming in Python
Automating Text File Operations with Python
The Amazing Library for Developing AI Applications in Python! Gradio
Data Type Operations in Python
1. List Creation Methods
1. Creating an Empty List: Use <span><span>[]</span></span> to create an empty list
empty_list = []
2. list() Constructor: Use <span><span>list()</span></span> to create an empty list
empty_list = list()
3. Creating from a String: Convert a string to a list of characters
char_list = list("Python")
4. Creating from a Tuple: Convert a tuple to a list
tuple_to_list = list((1, 2, 3))
5. Creating from Dictionary Keys: Convert dictionary keys to a list
dict_keys = list({'a':1, 'b':2}.keys())
2. Adding Elements to a List
6. append() Method: Add a single element to the end
nums = [1, 2]
nums.append(3)
7. extend() Method: Add multiple elements to the end
nums = [1, 2]
nums.extend([3, 4])
8. insert() Method: Insert an element at a specified position
letters = ['a', 'c']
letters.insert(1, 'b')
9. List Concatenation (+): Merge two lists
combined = [1, 2] + [3, 4]
10. List Repetition (*): Repeat list elements
repeated = [0] * 5
3. Accessing List Elements
11. Positive Indexing: Access elements using positive indexing
first = letters[0]
12. Negative Indexing: Access from the end using negative indexing
last = letters[-1]
13. Simple Slicing: Get a sublist
sub_list = nums[1:3]
14. Step Slicing: Slicing with a step
every_other = nums[::2]
15. Reverse Slicing: Reverse the list
reversed_list = nums[::-1]
16. Accessing Nested Lists: Access multi-dimensional lists
matrix = [[1,2], [3,4]]
element = matrix[0][1]
4. Modifying List Elements
17. Modifying a Single Element: Modify by index
nums[1] = 99
18. Slicing Modification: Replace a slice
nums[1:3] = [8, 9]
19. Slicing Deletion: Delete a slice using an empty list
nums[1:3] = []
5. Deleting List Elements
20. remove() Method: Delete the first matching value
nums.remove(2)
21. del Statement: Delete an element at a specified index
del nums[1]
22. del Slice: Delete a slice
del nums[1:3]
23. pop() Method: Delete and return the last element
last = nums.pop()
24. pop(index) Method: Delete and return the specified element
second = nums.pop(1)
25. clear() Method: Clear the entire list
nums.clear()
6. Searching and Counting in Lists
26. in Operator: Check if an element exists
exists = 2 in nums
27. not in Operator: Check if an element does not exist
missing = 5 not in nums
28. index() Method: Find the index of an element
position = letters.index('b')
29. count() Method: Count occurrences of an element
total = nums.count(1)
7. Getting List Information
30. len() Function: Get the length of the list
length = len(nums)
31. max() Function: Get the maximum value
maximum = max(nums)
32. min() Function: Get the minimum value
minimum = min(nums)
33. sum() Function: Calculate the sum of a numeric list
total = sum(nums)
8. Sorting and Reversing Lists
34. sort() Method: In-place ascending sort
nums.sort()
35. sort(reverse=True): In-place descending sort
nums.sort(reverse=True)
36. sort(key=len): Sort by string length
words.sort(key=len)
37. sorted() Function: Return a new sorted list
new_list = sorted(nums)
38. reverse() Method: In-place reverse the list
nums.reverse()
9. Copying and Comparing Lists
39. copy() Method: Create a shallow copy
new_nums = nums.copy()
40. Slicing Copy: Create a shallow copy using [:]
new_nums = nums[:]
41. deepcopy: Create a deep copy
import copy
deep_copy = copy.deepcopy(nested_list)
42. List Comparison (==): Check if contents are the same
is_equal = [1,2] == [1,2]
43. List Comparison (>): Compare in lexicographical order
is_greater = [2,1] > [1,2]
10. Advanced List Operations
44. List Comprehension: Create a new list
squares = [x**2 for x in range(5)]
45. Conditional List Comprehension: List comprehension with conditions
evens = [x for x in range(10) if x%2==0]
46. Nested List Comprehension: Multi-dimensional list comprehension
matrix = [[1,2], [3,4]]
flattened = [num for row in matrix for num in row]
47. zip() Function: Iterate over multiple lists in parallel
for a, b in zip(list1, list2):
print(a, b)
48. enumerate() Function: Get index and value
for index, value in enumerate(letters):
print(index, value)
49. any() Function: Check if any value is true
has_true = any([False, True, False])
50. all() Function: Check if all values are true
all_true = all([True, True, True])
These 50 commonly used list operations in Python cover everything from basic creation, addition, deletion, and modification to advanced operations such as list comprehension, zip, and enumerate. Mastering these methods will greatly enhance your Python programming efficiency.
“There is no secret, just practice!” Use them as needed. If you find this article useful, feel free to like, share, bookmark, comment, and recommend ❤!——Join the Knowledge Community and Learn with More People——
https://ima.qq.com/wiki/?shareId=f2628818f0874da17b71ffa0e5e8408114e7dbad46f1745bbd1cc1365277631c
https://wiki.ima.qq.com/knowledge-base-share?shareId=66042e013e5ccae8371b46359aa45b8714f435cc844ff0903e27a64e050b54b5