Python Find in List
Python Find in List:
Sure, you can find an element in a list in Python using the in
operator or the list’s index()
method.
in
Operator:
my_list = [1, 2, 3, 4, 5]
if 3 in my_list:
print("Found in list")
else:
print("Not found in list")
index()
method:
my_list = [1, 2, 3, 4, 5]
try:
index = my_list.index(3)
print(f"Found at index {index}")
except ValueError:
print("Not found in list")
Note: The index()
method raises a ValueError
if the element is not found in the list. Therefore, it’s best to use it in a try-except block to handle such scenarios.
Remember, these methods can only find the first occurrence of the element in the list. If you want to find all occurrences, you’ll need to use a loop or a list comprehension. Here’s how you can do it using list comprehension:
my_list = [1, 2, 3, 4, 3, 5, 3]
indices = [i for i, x in enumerate(my_list) if x == 3]
print(indices) # This will print: [2, 4, 6]
The above code will find all indices at which the number 3 appears in the list.
Python Training Demo Day 1
Conclusion:
Unogeeks is the No.1 IT Training Institute for Python Training. Anyone Disagree? Please drop in a comment
You can check out our other latest blogs on Python here – Python Blogs
You can check out our Best In Class Python Training Details here – Python Training
Follow & Connect with us:
———————————-
For Training inquiries:
Call/Whatsapp: +91 73960 33555
Mail us at: info@unogeeks.com
Our Website ➜ https://unogeeks.com
Follow us:
Instagram: https://www.instagram.com/unogeeks
Facebook: https://www.facebook.com/UnogeeksSoftwareTrainingInstitute
Twitter: https://twitter.com/unogeeks