How to Check if Tuple Exists in a List in Python
Table of Contents
Python is a popular programming language due to how simple it is to use its built-in data structures.
The list and tuple data structures are both used to store data in Python.
Sometimes when you have a list of tuples, you want to know if a specific tuple exists in the list.
In this post, we'll learn how you check if your list of tuples contains a specific tuple.
Check if a tuple exists in a list of tuples
To start off, let's define a list of tuples:
PYTHONlist = [
("a", "b"),
("c", "d"),
("e", "f")
]
In this example, we have a 3-element list of tuples, each with a pair of strings.
Let's define the value we want to check:
PYTHONlist = [
("a", "b"),
("c", "d"),
("e", "f")
]
value = ("a", "b")
Now let's check if this value is in the list by using the in
keyword.
PYTHONlist = [
("a", "b"),
("c", "d"),
("e", "f")
]
value = ("a", "b")
if value in list:
print("Value exists in list!")
else:
print("Value does not exist in list!")
BASHValue exists in list!
The check will return a boolean value of True
if the value exists in the list, or False
if it does not.
Since the value was indeed in the list, it returned True
and we ran the code block inside, which was just a print statement.
Likewise, if you can test it with a value that does not exist:
PYTHONlist = [
("a", "b"),
("c", "d"),
("e", "f")
]
value = ("g", "h")
if value in list:
print("Value exists in list!")
else:
print("Value does not exist in list!")
BASHValue does not exist in list!
Since the value was not in the list, it returned False
and the second code block ran.
Conclusion
In this post, we learned how to check if a tuple exists in a list of tuples.
Simply use the in
keyword with your desired value and list to get a boolean.
Thanks for reading!
- Managing PHP Dependencies with Composer
- Getting Started with Electron
- How to Serve Static Files with Nginx and Docker
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to deploy a MySQL Server using Docker
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications