For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
In Python—a language revered for its versatility—list methods stand out as integral tools for efficient data management. Mastery over these methods translates to significant strides in programming, enabling seamless data manipulation, organization, and retrieval. This tutorial on list methods in Python aims to provide a detailed walkthrough, ensuring professionals harness the full potential of lists, making them indispensable assets in real-world applications and complex projects.
Lists in Python are the backbone of numerous applications, often compared to dynamic arrays in other languages. Their ability to hold diverse data types, coupled with an array of built-in methods, renders them essential for both beginners and seasoned developers. In this tutorial, we will unravel the layers of Python list methods, focusing on their syntax, usage, and real-world implications. Our intent is to transform your perspective on lists, transitioning from basic understanding to in-depth expertise.
In Python, lists are a versatile and commonly used data structure. They are used to store collections of items, and Python provides various methods for manipulating and working with lists. Here are some important functions of the Python list, along with examples of how to use them:
1. append(): Adds an element to the end of the list.
Code:
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits) # Output: ["apple", "banana", "cherry", "orange"]
2. insert(): Inserts an element at a specified position in the list.
Code:
fruits = ["apple", "banana", "cherry"]
fruits.insert(1, "orange")
print(fruits) # Output: ["apple", "orange", "banana", "cherry"]
3. remove(): Removes the first occurrence of a specified element from the list.
Code:
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits) # Output: ["apple", "cherry"]
4. pop(): Removes and returns an element at the specified index. If no index is provided, it removes and returns the last element.
Code:
fruits = ["apple", "banana", "cherry"]
removed_fruit = fruits.pop(1)
print(removed_fruit) # Output: "banana"
5. index(): Returns the index of the first occurrence of a specified element.
Code:
fruits = ["apple", "banana", "cherry"]
index = fruits.index("cherry")
print(index) # Output: 2
6. count(): Returns the number of times a specified element appears in the list.
Code:
fruits = ["apple", "banana", "cherry", "banana"]
count = fruits.count("banana")
print(count) # Output: 2
7. sort(): Sorts the list in ascending order.
Code:
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
numbers.sort()
print(numbers) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
8. reverse(): Reverses the order of elements in the list.
Code:
fruits = ["apple", "banana", "cherry"]
fruits.reverse()
print(fruits) # Output: ["cherry", "banana", "apple"]
9. extend(): Appends the elements of another list to the end of the current list.
Code:
fruits = ["apple", "banana", "cherry"]
more_fruits = ["orange", "grape"]
fruits.extend(more_fruits)
print(fruits) # Output: ["apple", "banana", "cherry", "orange", "grape"]
Code:
# Initialize a list
fruits = ["apple", "banana", "cherry"]
# Method 1: Using append() to add an element to the end of the list
fruits.append("orange")
# Method 2: Using insert() to add an element at a specified position
fruits.insert(1, "grape")
# Method 3: Using the + operator to concatenate lists and add multiple elements
fruits = fruits + ["kiwi", "mango"]
# Method 4: Using list comprehension to add elements based on some logic
fruits = [fruit + " juice" for fruit in fruits]
# Method 5: Using extend() to append elements from another list to the end
more_fruits = ["pineapple", "strawberry"]
fruits.extend(more_fruits)
# Method 6: Using slicing to insert elements at a specific position
fruits[2:2] = ["watermelon"]
# Print the final list of fruits
print(fruits)
This program demonstrates the use of various methods to add elements to the fruits list, including append(), insert(), + operator, list comprehension, extend(), and slicing.
Code:
# Initialize a list
fruits = ["apple", "banana", "cherry", "orange", "grape", "kiwi"]
# Method 1: Using pop() to remove and return an element by index
removed_fruit = fruits.pop(2) # Remove the third element ("cherry")
print("Removed fruit:", removed_fruit)
# Method 2: Using remove() to remove the first occurrence of a specific element
fruits.remove("orange")
# Method 3: Using del statement to remove an element by index
del fruits[0] # Remove the first element ("apple")
# Method 4: Using slicing to remove a range of elements
fruits[1:3] = [] # Remove the second and third elements ("banana" and "grape")
# Print the final list of fruits
print("Updated fruits list:", fruits)
The above code demonstrates four different methods for removing elements from a list in Python. Let us understand each method:
fruits.pop(2) removes and returns the element at index 2 (which is "cherry") from the fruits list. The removed element is assigned to the variable removed_fruit. After this operation, the list fruits no longer contains "cherry."
fruits.remove("orange") removes the first occurrence of the element "orange" from the fruits list. This method removes elements based on their values, not their indices.
del fruits[0] deletes the element at index 0 (which is "apple") from the fruits list. The del statement allows you to remove elements by specifying their indices.
fruits[1:3] = [] uses slicing to remove elements from index 1 to 2 (inclusive) in the fruits list. In this case, it removes "banana" (index 1) and "grape" (index 2). The empty list [] effectively removes the specified range of elements.
After applying these methods, the code prints the updated fruits list, which contains the elements that haven't been removed. In the final list, "cherry," "orange," "apple," "banana," and "grape" have been removed, leaving only "kiwi."
Code:
def remove_duplicates(input_list):
unique_list = []
for item in input_list:
if item not in unique_list:
unique_list.append(item)
return unique_list
my_list = [1, 2, 2, 3, 4, 4, 5]
result = remove_duplicates(my_list)
print(result)
Explanation:
This program defines a function remove_duplicates that takes a list as input. Inside the function, it initializes an empty list called unique_list to store unique elements. It iterates through each item in the input list and checks whether the item is already in the unique_list. If the item is not in the unique_list, it appends it, ensuring only unique elements are added. Finally, it returns the unique_list without duplicates.
Code:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
transposed_matrix = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(transposed_matrix)
Explanation:
This program uses list comprehension to transpose a matrix represented as a list of lists.
The nested list comprehension iterates through the rows and columns of the original matrix, swapping rows and columns to create the transposed matrix.
Code:
def merge_sorted_lists(list1, list2):
merged_list = []
i = j = 0
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
merged_list.append(list1[i])
i += 1
else:
merged_list.append(list2[j])
j += 1
merged_list.extend(list1[i:])
merged_list.extend(list2[j:])
return merged_list
list1 = [1, 3, 5, 7]
list2 = [2, 4, 6, 8]
result = merge_sorted_lists(list1, list2)
print(result)
Explanation:
This program defines a function merge_sorted_lists that takes two sorted lists as input and returns a merged and sorted list. It uses two pointers i and j to iterate through both lists while comparing elements. Elements from the two lists are compared, and the smaller one is added to the merged_list. After reaching the end of one of the lists, the remaining elements from the other list are appended to the merged_list. The result is a merged and sorted list.
Python's list methods are pivotal, bridging the gap between simple data storage and intricate data manipulations. Their flexibility and adaptability reinforce Python's reputation as a robust programming language. As we culminate our exploration of list methods in Python, it's evident that a thorough understanding of these tools can significantly elevate one's programming acumen. For those passionate about refining their skills and delving deeper into Python's treasures, upGrad offers a plethora of courses that resonate with today's industry demands.
1. How do list methods in Python differ from tuple methods in Python?
While both deal with ordered collections, list methods emphasize mutability, whereas tuple methods are restricted due to the immutable nature of tuples.
2. Is there a distinction between list operations in Python and Python set methods?
Indeed, list operations cater to ordered collections, while set methods address unique, unordered collections.
3. How does the "extend" method offer advantages over using "+" for merging lists in Python?
The "extend" method modifies the original list, ensuring memory efficiency, whereas "+" creates an entirely new list, consuming more memory.
4. Could you draw a contrast between string methods in Python and the discussed list methods?
String methods are tailored for the string data type. Although there are overlapping operations, such as determining length, string methods can't manipulate data like lists due to strings' immutable nature.
5. Apart from "copy", are there other avenues to duplicate the contents of a Python list?
Certainly, techniques like slicing ([:]) or employing the list() constructor offer alternatives for list replication.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.