Example:
tuple = ("python", "includehelp", 43, 54.23)
List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of an ordered set of values enclosed in square brackets []
Example:
list = [3 ,1, 5, 7]
List of tuples is a list whose each element is a tuple.
Example:
tupList = [("python", 7), ("learn" , 1), ("programming", 7), ("code" , 3)]
List Comprehension: It is an easy and compact way of creating a list by performing multiple operations on a data structure.
Now, let's get back to our problem and see how to solve it?
Here are sample inputs and outputs for the problem to understand the program's working.
Input:
tupList:
[("py_t_hon", 4), ("p_ro_gra_m", 5)] char = '_'
Output:
[("python", 4), ("program", 5)]
To remove the given character from the first element of each tuple. We need to traverse the list and for each tuple take the first elements and check for the presence of the given character in it, if it is present delete the character otherwise do nothing.
Deleting the character from the string can be done in multiple ways in python. We will be discussing some of them clubbed with other methods to perform the required task.
Method 1:
One way to find the solution is by using list comprehension to iterate over the list of tuples and then for the first element of each tuple, we will remove the character using replace() method.
replace() method takes in two parameters, first, the character to be replaced, and second will be the character that replaces it.
Syntax:
Program to remove the given character from the first element of Tuple
Output:
Method 2:
An alternate way to solve the problem is by replacing the replace() method with translate(). We will simply use list comprehension and use the translate() method in it to remove the character.
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer