- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove tuple from list of tuples if not containing any character in Python
When it is required to remove a tuple from a list of tuples based on a given condition, i.e the tuple doesn't contain a specific character, the list comprehension can be used.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). A list of tuple basically contains tuples enclosed in a list.
The list comprehension is a shorthand to iterate through the list and perform operations on it.
Below is a demonstration for the same −
Example
my_list = [('. ', 62), ('Mark', 5), ('Paul.', 21), ('.....', 0), ('-Jane', 115), ('Jake', 15), ('::', 63), ('John', 3), ('--', 1), ('there', 82), ('Harold', 100)] my_result = [(a, b) for a, b in my_list if any(c.isalpha() for c in a)] print("The tuple that doesn't contain any character has been removed") print("The resultant list of tuple is :") print(my_result)
Output
The tuple that doesn't contain any character has been removed The resultant list of tuple is : [('Mark', 5), ('Paul.', 21), ('-Jane', 115), ('Jake', 15), ('John', 3), ('there', 82), ('Harold', 100)]
Explanation
- A list of tuple is defined, and is displayed on the console.
- The list of tuple is iterated over, and checked whether it belongs to the alphabet family.
- This operation's data is stored in a variable.
- This variable is the output that is displayed on the console.
Advertisements