You are currently viewing Python List Operations

Python list is a versatile data structure that allows you to store a collection of elements in a specific order. Each element in the list is assigned an index, starting from 0, which indicates its position within the list. List operations refer to the actions or functions that can be applied to the elements contained within a list. These operations provide various ways to manipulate, access, modify, or analyze the data stored in the list.

Advertisements

You can use several built-in functions of the list like, append(), extend(), insert(), remove(), pop(), Slice(), min() & max(), reverse(), count(), index(), sort(), and clear() to perform various operations upon the list elements. In this article, I will explain list operations by using all these functions with examples

The list operations you mentioned are indeed commonly used in Python programming. Here’s a brief explanation of each operation.

  • extend() – Appends the elements of another iterable (e.g., another list) to the end of the list.
  • insert() – Inserts an element at a specific index in the list.
  • append() – Adds an element at the end of the list.
  • remove() – Removes the first occurrence of a specified element from the list.
  • pop() – Removes and returns the element at a specified index in the list.
  • Slice – Allows you to extract a portion (sublist) of the list using a specified range of indices.
  • reverse() – Reverses the order of elements in the list.
  • min() and max() – Returns the minimum and maximum values in the list, respectively.
  • Concatenate – Combines two lists into a single list.
  • count() – Returns the number of occurrences of a specified element in the list.
  • Multiply – Repeats the list a specified number of times, creating a new list.
  • sort() – Sorts the list in ascending order (or based on specified sorting criteria).
  • index() – Returns the index of the first occurrence of a specified element in the list.
  • clear() – Removes all elements from the list, making it empty.

1. Quick Examples of List Operations

If you are in a hurry, below are some quick examples of list operations.


# Quick examples of list operations

# Initialize the list
technology = ['Spark', 'Python', 'Pyspark']

# Example 1: Add "Hadoop" to the list
technology.append('Hadoop')

# Example 2: Extend list
technology.extend(['Hadoop','C++','Java'])

# Example 3: Using remove()
technology.remove('Python')

# Example 4: Inserting an element 
# At a specific index
technology.insert(1, 'Hadoop')

# Example 5: Use pop() method
# To remove the last element
result = technology.pop()

# Example 6: Using slice()
result = technology[1:3]

# Example 7: Use list.count() method
count = mylist.count("Python")

# Example 8: Get the smallest element
# Using min() function
min_value = min(mylist)

# Example 9: Get maximum value 
# Using max() Function
max_value = max(mylist)

# Example 10: Using reverse()
mylist.reverse()

# Example 11: Multiply list 
result = mylist * 2

# Example 12: Python list index() method 
result = mylist.index('Python')

# Example 13: Sort the list in ascending order 
mylist.sort()

# Example 14: Clear a list using clear()
mylist.clear()

# Example 15: Concatenated list 
# Using + Operator
list1 = [1, 3, 5]
list2 = [7, 9, 11]
concat_list = list1 + list2 

2. List Operations in Python

Lists are mutable hence, you can do various operations over the list elements such as adding, removing, appending, sorting, and accessing. Below are some of the most commonly used list operations.

2.1 Create an Empty List Using Square Brackets []

Python lists are represented in square brackets and the elements are separated by a comma, so to create an empty list just use the empty square brackets [] without any elements. Here is an example.


# Create empty list using []
mylist = []

# Print empty list
print(mylist)

# Output:
# []

2.2 List append() Function

You can use list.append() to append an item or element to a list, (element can be a string, list e.t.c). For example, if you have a list called technology and you want to append an element 'Hadoop' at the end, use this function. Here, is an example.


# Consider a list
technology = ['Spark', 'Python', 'Pyspark']
print("Actual List",technology)

# Add 'Hadoop' to the list
technology.append('Hadoop')
print("Updated List: ",technology)

Yields below output.

python list operations

2.3 Python List extend()

By using the list.extend() method to add the elements to the existing list. Note that this method modifies the existing list with the new elements and the elements are added at the end of the original list.


# Consider a list of strings
technology = ['Spark', 'Python', 'Pyspark']
print("Actual List",technology)

# Extend list
technology.extend(['Hadoop','C++','Java'])
print("Final List: ",technology)

Yields below output.

python list operations

2.4 Remove Element by Value

You can remove an element from a list using remove() method along with a specified value. This method searches for the first occurrence of the specified value in the list and removes it.

In the below example, you have a list of strings called technology, and you want to remove the string 'Python' from the list using this method. After removing the string 'Python' from the technology list updated list will be ['Spark','Pyspark'].


# Consider a list of strings
technology = ['Spark', 'Python', 'Pyspark']
print("Actual List",technology)

# Using remove()
technology.remove('Python')
print("Final List: ",technology)

# Output:
# Actual List ['Spark', 'Python', 'Pyspark']
# Final List:  ['Spark', 'Pyspark']

2.5  Python List insert() Examples

You can use the insert() method to insert an element at a specific index in a list. For example, you have a list of strings called technology, and you want to insert the string 'Hadoop' at index 1 in the list.

In this program, the string 'Hadoop' is inserted at the index 1 of the technology list using the insert() method. The updated list, ['Spark', 'Hadoop', 'Python', 'Pyspark']is then printed. The existing elements in the list shift to the right to accommodate the inserted element.


# Consider a list of strings
technology = ['Spark', 'Python', 'Pyspark']
print("Actual List",technology)

# Inserting an element 
# At a specific index
technology.insert(1, 'Hadoop')
print("Final List: ",technology)

# Output:
# Actual List ['Spark', 'Python', 'Pyspark']
# Final List:  ['Spark', 'Hadoop', 'Python', 'Pyspark']

2.6 pop() Method

You can use pop() method to remove and return the item from the list at a specified index position. It takes the index as an option argument, and when specified it returns the value of the given index. If an index is not provided, by default this method will remove the last item from the list.

Let’s initialize the list with some items and call pop()method over the list with no argument, it will remove and return the last item which is 'Pyspark'.


# Initialize the list
technology = ['Spark', 'Python', 'Pyspark']

# Use pop() method
# To remove the last element
result = technology.pop()
print("Popped item:", result)
print("List after pop():",technology)

# Output:
# Popped item: Pyspark
# List after pop(): ['Spark', 'Python']

2.7 Use Slicing

You can slice a list using positive indexes, which refer to the position of the elements from the beginning of the list. Following are examples of using the slice notation to slice a list in Python, here I will use the combination of start, stop, and step values with examples.

For example, you can use the slice operator [1:3] to extract a subset of the list containing elements with indexes 1 and 2. From the below example, it returns ‘Python’ and ‘Pyspark’.

Related: You can use negative indexing to slice the list from the end of the list.


# Initialize the list
technology = ['Spark', 'Python', 'Pyspark']

# Using slice()
result = technology[1:3]
print(result)

# Output:
# ['Python', 'Pyspark']

2.8 Python List count() Method

You can use the count() method to get the number of times an element is present in a list. It is a useful method for counting the occurrences of a particular element within a list.

You can use the count() method of a list to return the count of how many times a specified object occurs in the list. For example, mylist.count("Python") returns the count of how many times the value "Python" appears in the list mylist, which is 1. The count is then assigned to the variable count and printed to the console.


# Initialize list
mylist = ["Spark", "Python", "Pyspark"]
print("Original list: ", mylist)

# Use list.count() method
count = mylist.count("Python")
print('Count the number of lists of python:', count)

# Output:
# Original list:  ['Spark', 'Python', 'Pyspark']
# Count the number of lists of python: 1

2.9 List min() & max() Method

You can use the min() function in Python to get the minimum value from a list or an iterable. For example, the min() function is applied to mylist, and it returns the smallest element according to the lexicographic order (based on string comparison). In this case, "Pyspark" is considered the smallest element in the list because it comes first in lexicographic order.


# Initialize list
mylist = ["Spark", "Python", "Pyspark"]
print("Original list: ", mylist)

# Get smallest element
# Using min() Function
min_value = min(mylist)
print("Get smallest element is: ", min_value)

# Output:
# Original list:  ['Spark', 'Python', 'Pyspark']
# Get smallest element is:  Pyspark 

Similarly, you can use the max() function of Python to get the maximum value from a list or an iterable. For example, the max() function is applied to mylist, and it returns the maximum value according to the lexicographic order (based on string comparison). In this case, "Spark" is considered the maximum value because it comes last in lexicographic order among the three elements in the list.


# Initialize list
mylist = ["Spark", "Python", "Pyspark"]
print("Original list: ", mylist)

# Get maximum value 
# Using max() Function
max_value = max(mylist)
print("Get maximum value: ", max_value)

# Output:
# Original list: ['Spark', 'Python', 'Pyspark']
# Get maximum value: Spark

2.10 Using reverse() Method

The list reverse() method is used to reverse the elements in the list. The below examples take the list of strings and reverse the elements in the list.


# Initialize list
mylist = ["Spark", "Python", "Pyspark"]
print("Original list: ", mylist)

# Using reverse()
mylist.reverse()
print("Reversed List: ",mylist)

# Output:
# Original list:  ['Spark', 'Python', 'Pyspark']
# Reversed List:  ['Pyspark', 'Python', 'Spark']

2.11 List Concatenate

You can use the + operator to concatenate the lists. Simply, apply the operator between the lists and get the concatenated list. In this program, the + operator is used to concatenating list1 and list2. It creates a new list that contains all the elements from list1 followed by all the elements from list2, resulting in the concat_list. Using the + operator is a straightforward and efficient way to concatenate lists in Python.


# Initialization list
list1 = [1, 3, 5]
list2 = [7, 9, 11]

# Concatenated list 
# Using + Operator
concat_list = list1 + list2 
print ("The concatenated list is:", concat_list)

# Output:
# The concatenated list is: [1, 3, 5, 7, 9, 11]

2.12 Multiply

You can multiply lists using the * operator in Python. For example, the first initializes a list called mylist with three elements. Then, the * operator is used to multiply the list by 2, which creates a new list that repeats the original list elements twice.


# Initialize list
mylist = ["Spark", "Python", "Pyspark"]
print("Original list: ", mylist)

# Multiply list 
result = mylist * 2
print("Multiplied the list: ",result)

# Output:
# Original list:  ['Spark', 'Python', 'Pyspark']
# Multiplied the list:  ['Spark', 'Python', 'Pyspark', 'Spark', 'Python', 'Pyspark']

2.13 Python List index() method

The Python list.index() method will return the index position of the given element that exists in the list. If the element is not found, ValueError is raised. To overcome this error, we can specify this method inside the try-except block.

Let’s create a list of mylist and return the “Python” index position. In the below example, you can see that “Python” exists in the list hence, the index is returned as 1. Note that in Python the index starts from 0.


# Initialize list
mylist = ["Spark", "Python", "Pyspark"]

# Python list index() method 
result = mylist.index('Python')
print(result)

# Output:
# 1

2.14 Python List sort() Method

By using the Python list sort() function to sort the list of strings in ascending order, For strings ascending order means it sorts in alphabetical order. The sort() method by default sorts in ascending order


# Sort the list in ascending order 
mylist = ["Spark", "Python", "Pyspark"]
mylist.sort()
print(mylist)

# Output:
# ['Pyspark', 'Python', 'Spark']

2.15 List clear() Method

You can use the clear() method to remove all the elements from a list. For example, create a list with a set of values and call the clear() method to remove all the elements from the list. After that, call the print() function to show list is empty on the console.


# Initialize list
mylist = ["Spark", "Python", "Pyspark"]
print("Original list: ", mylist)

# Clear a list using clear()
mylist.clear()
print("After clearing the list: ", mylist)

# Output:
# Original list:  ['Spark', 'Python', 'Pyspark']
# After clearing the list:  []

2.16 List copy() Method

You can use the copy() method is a built-in method for Python lists that creates a shallow copy of the list and returns the copied list. This method does not take any arguments and returns a new list object that contains references to the same objects as the original list.

In the below example, first, define a list called mylist with five elements. You then create a new list called copied_list by calling the copy() method on mylist.


# Initialize list
mylist = ["Spark", "Python", "Pyspark"]
print("Original list: ", mylist)

# Copying a list
# Using the copy() method
copied_list = mylist.copy()
print("Copied the list: ", copied_list)

# Output:
# Original list:  ['Spark', 'Python', 'Pyspark']
# Copied the list:  ['Spark', 'Python', 'Pyspark']

Conclusion

In this article, I have explained various Python list methods and techniques like append(), extend(), insert(), remove(), pop(), Slice, min() & max(), reverse(), count(), concatenate, multiply, index(), sort(), and clear() and using these methods how we can perform the list operations with examples.

Happy Learning !!