The list is a data structure in python that allows you to store multiple objects in one variable. If you have a list and want to traverse and skip a value in a list then this post is for you. In this article, you will know the various method to skip a value in a list in python.
How to create a List in Python?
You can create a list in python using the ” [] ” square brackets. For example, if I want to create a list of integers then I will use the square bracket with elements of the list of integer types.
Use the below lines of code to create a list.
my_list = [10, 20, 30, 40, 50]
print(my_list)
Output
[10, 20, 30, 40, 50]
Methods to skip a value in a list python
Let’s know all the methods to skip a value in a list in python.
Method 1: Using enumerate function
You can use the enumerate function to loop through the list and based on the condition skip the single element of the list.
The below code will skip the “40” element from the list and print the remaining elements.
my_list = [10, 20, 30, 40, 50]
for i, v in enumerate(my_list):
if v == 40:
continue
print(v)
Output

Method 2: Using list comprehension
In this method, you will skip the element of the list conditionally. For example, I want to skip the elements that are even or divisible by 2.
Execute the below lines of code.
my_list = [11, 21, 30, 41, 50]
my_list = [v for v in my_list if v % 2 == 0]
print(my_list)
Output

Method 3: Skipping element based on the index
You can also skip the elements from the list using the index position. Loop through the list and check the condition for the index. Execute the below code to execute it.
my_list = [10, 20, 30, 40, 50]
my_list = [v for i, v in enumerate(my_list) if i not in [0, 4]]
print(my_list)
Output

Method 4: Using filter and lambda function
The other method to skip the value of the list conditionally is the use of filter and lambda functions. You will pass the lambda function as an argument to the filter function.
The below code will skip the elements that are even.
my_list = [11, 21, 30, 41, 50]
my_list = filter(lambda x: x % 2 == 0, my_list)
print(list(my_list))
Output

Conclusion
In this article, you have learned all the methods to skip a value from the list in python. You can use any of the methods based on your requirement. I hope this article will help you. If you have any queries then please comment below. You can contact us for more help.
Leave a Reply