Python | Convert list of tuples into digits
Last Updated :
31 Mar, 2023
Given a list of tuples, the task is to convert it into list of all digits which exists in elements of list. Let’s discuss certain ways in which this task is performed.
Method #1: Using re The most concise and readable way to convert list of tuple into list of all digits which exists in elements of list is by using re.
Python3
# Python code to convert list of tuples into
# list of all digits which exists
# in elements of list.
# Importing
import re
# Input list initialization
lst = [(11, 100), (22, 200), (33, 300), (44, 400), (88, 800)]
# Using re
temp = re.sub(r'[\[\]\(\), ]', '', str(lst))
# Using set
Output = [int(i) for i in set(temp)]
# Printing output
print("Initial List is :", lst)
print("Output list is :", Output)
OutputInitial List is : [(11, 100), (22, 200), (33, 300), (44, 400), (88, 800)]
Output list is : [2, 1, 8, 4, 3, 0]
Method #2: Using itertools.chain() and lambda() This is yet another way to perform this particular task using lambda().
Python3
# Python code to convert list of tuples into
# list of all digits which exists
# in elements of list.
# Importing
from itertools import chain
# Input list initialization
lst = [(11, 100), (22, 200), (33, 300), (44, 400), (88, 800)]
# using lambda
temp = map(lambda x: str(x), chain.from_iterable(lst))
# Output list initialization
Output = set()
# Adding element in Output
for x in temp:
for elem in x:
Output.add(elem)
# Printing output
print("Initial List is :", lst)
print("Output list is :", Output)
OutputInitial List is : [(11, 100), (22, 200), (33, 300), (44, 400), (88, 800)]
Output list is : {'4', '3', '2', '1', '8', '0'}
Method #3: Using list(),map(),join() and set() methods
Initially we convert list containing tuple of integers to list containing tuple of strings.Later we will concatenate the string(obtained by joining tuple strings) to an empty string.And then use set to remove duplicates.Finally convert them to integer type and print output list
Python3
# Python code to convert list of tuples into
# list of all digits which exists
# in elements of list.
# Input list initialization
lst = [(11, 100), (22, 200), (33, 300), (44, 400), (88, 800)]
p=""
for i in lst:
x=list(map(str,i))
p+="".join(x)
p=list(map(int,set(p)))
# Printing output
print("Initial List is :", lst)
print("Output list is :", p)
OutputInitial List is : [(11, 100), (22, 200), (33, 300), (44, 400), (88, 800)]
Output list is : [8, 3, 2, 4, 0, 1]
Time complexity: O(n), where n is the length of list
Auxiliary Space: O(m), where m is the number of digits.
Method #4: Using list comprehension and the isdigit method
You can use a list comprehension and the isdigit method to extract all the digits from the tuples in the list. The isdigit method returns True if a character is a digit, and False otherwise.
Python3
# Initialize the list
lst = [(11, 100), (22, 200), (33, 300), (44, 400), (88, 800)]
# Extract the digits using a list comprehension and the isdigit method
digits = set([c for t in lst for c in str(t) if c.isdigit()])
# Print the resulting list
print("The list of digits:", digits)
#This code is contributed by Edula Vinay Kumar Reddy
OutputThe list of digits: {'0', '8', '1', '2', '3', '4'}
Time complexity is O(n)
Auxiliary Space is O(m), where n is the length of the list and m is the number of digits.
Method #5: Using nested loops and string conversion
Step-by-step approach:
- Initialize the input list lst with the given values.
- Initialize an empty list digits to store the extracted digits.
- Loop through each tuple tup in the input list.
- Loop through each item in the current tuple.
- Loop through each character char in the string representation of the current item.
- Check if the current character is a digit using the isdigit() method.
- If it is a digit, convert it to an integer using the int() function and append it to the digits list.
- Use the set() function to remove duplicates from the digits list and convert it back to a list.
- Print the initial list and the output list.
Below is the implementation of the above approach:
Python3
# Input list initialization
lst = [(11, 100), (22, 200), (33, 300), (44, 400), (88, 800)]
# Using nested loops and string conversion
digits = []
for tup in lst:
for item in tup:
for char in str(item):
if char.isdigit():
digits.append(int(char))
# Using set to remove duplicates
Output = list(set(digits))
# Printing output
print("Initial List is :", lst)
print("Output list is :", Output)
OutputInitial List is : [(11, 100), (22, 200), (33, 300), (44, 400), (88, 800)]
Output list is : [0, 1, 2, 3, 4, 8]
Time complexity: O(n*m), where n is the length of the input list and m is the maximum length of the items in the tuples (assuming integer items only).
Auxiliary space: O(k), where k is the total number of digits in all the items in the input list.
Method #6: Using numpy.ravel():
- Import the numpy library.
- Initialize a list of tuples called last.
- Use numpy's ravel() method to convert the list of tuples to a 1-D numpy array called arr.
- Use a list comprehension and the isdigit() method to extract the digits from the array and convert them to integers.
- Use set() to remove any duplicates in the list of digits.
- Convert the set back to a list called digits.
- Print the original list and the resulting list.
Python3
import numpy as np
# Initialize the list
lst = [(11, 100), (22, 200), (33, 300), (44, 400), (88, 800)]
# Convert the list of tuples to a 1-D numpy array using ravel() method
arr = np.array(lst).ravel()
# Extract the digits using a list comprehension and the isdigit method
digits = [int(d) for d in ''.join(map(str, arr)) if d.isdigit()]
# Remove duplicates using set
digits = list(set(digits))
# Print the resulting list
print("Initial List is :", lst)
print("Output list is :", digits)
Output
Initial List is : [(11, 100), (22, 200), (33, 300), (44, 400), (88, 800)]
Output list is : [0, 1, 2, 3, 4, 8]
The time complexity of this code is O(n), where n is the total number of digits.
The space complexity of this code is O(n), where n is the total number of digits.
Similar Reads
Python | Convert list of tuples into list
In Python we often need to convert a list of tuples into a flat list, especially when we work with datasets or nested structures. In this article, we will explore various methods to Convert a list of tuples into a list. Using itertools.chain() itertools.chain() is the most efficient way to flatten a
3 min read
Python - Convert a list into tuple of lists
When working with data structures in Python, there are times when we need to convert a list into a tuple of smaller lists.For example, given a list [1, 2, 3, 4, 5, 6], we may want to split it into a tuple of two lists like ([1, 2, 3], [4, 5, 6]). We will explore different methods to achieve this con
3 min read
Convert Dictionary to List of Tuples - Python
Converting a dictionary into a list of tuples involves transforming each key-value pair into a tuple, where the key is the first element and the corresponding value is the second. For example, given a dictionary d = {'a': 1, 'b': 2, 'c': 3}, the expected output after conversion is [('a', 1), ('b', 2
3 min read
Python | Convert list of tuples to list of list
Converting list of tuples to list of lists in Python is a task where each tuple is transformed into list while preserving its elements. This operation is commonly used when we need to modify or work with the data in list format instead of tuples.Using numpyNumPy makes it easy to convert a list of tu
3 min read
Convert List of Dictionary to Tuple list Python
Given a list of dictionaries, write a Python code to convert the list of dictionaries into a list of tuples.Examples: Input: [{'a':[1, 2, 3], 'b':[4, 5, 6]}, {'c':[7, 8, 9], 'd':[10, 11, 12]}] Output: [('b', 4, 5, 6), ('a', 1, 2, 3), ('d', 10, 11, 12), ('c', 7, 8, 9)] Below are various methods to co
5 min read
Convert List to Tuple in Python
The task of converting a list to a tuple in Python involves transforming a mutable data structure list into an immutable one tuple. Using tuple()The most straightforward and efficient method to convert a list into a tuple is by using the built-in tuple(). This method directly takes any iterable like
2 min read
Python | List of tuples to dictionary conversion
Interconversions are always required while coding in Python, also because of the expansion of Python as a prime language in the field of Data Science. This article discusses yet another problem that converts to dictionary and assigns keys as 1st element of tuple and rest as it's value. Let's discuss
3 min read
Python - Convert Float to digit list
We are given a floating-point number and our task is to convert it into a list of its individual digits, ignoring the decimal point. For example, if the input is 45.67, the output should be [4, 5, 6, 7].Using string manipulationIn this method, the number is converted to a string and then each charac
4 min read
Python | Dictionary to list of tuple conversion
Inter conversion between the datatypes is a problem that has many use cases and is usual subproblem in the bigger problem to solve. The conversion of tuple to dictionary has been discussed before. This article discusses a converse case in which one converts the dictionary to list of tuples as the wa
5 min read
Python | Convert Integral list to tuple list
Sometimes, while working with data, we can have a problem in which we need to perform type of interconversions of data. There can be a problem in which we may need to convert integral list elements to single element tuples. Let's discuss certain ways in which this task can be performed. Method #1 :
3 min read