Python | Convert String to list of tuples
Sometimes, while working with data, we can have a problem in which we have a string list of data and we need to convert the same to list of records. This kind of problem can come when we deal with a lot of string data. Let’s discuss certain ways in which this task can be performed.
Method #1: Using zip() + split() + list slicing
The combination of the above functionalities can be used to solve this problem. In this, first, the string is converted to list of strings and then required tuples are made using zip() and list slicing functionality.
Python3
test_string = "GFG is best Computer Science Portal"
print ( "The original string : " + str (test_string))
temp = test_string.split()
res = list ( zip (temp[:: 2 ], temp[ 1 :: 2 ]))
print ( "List after String to tuple conversion : " + str (res))
|
Output :
The original string : GFG is best Computer Science Portal List after String to tuple conversion : [(‘GFG’, ‘is’), (‘best’, ‘Computer’), (‘Science’, ‘Portal’)]
Time complexity: O(N), where n is the length of the input string.
Auxiliary space: O(N/2), as we create a list of tuples with half the size of the input string (assuming an even number of words).
Method #2: Using iter() + split() + next() + generator expression
This is yet another method to perform this particular task. In this, we use iterator to reach the to solution this task. The method is same as above, just iterator is used for faster access.
Python3
test_string = "GFG is best Computer Science Portal"
print ( "The original string : " + str (test_string))
temp = iter (test_string.split())
res = [(ele, next (temp)) for ele in temp]
print ( "List after String to tuple conversion : " + str (res))
|
Output :
The original string : GFG is best Computer Science Portal List after String to tuple conversion : [(‘GFG’, ‘is’), (‘best’, ‘Computer’), (‘Science’, ‘Portal’)]
Method #3: Using re.findall() and list comprehension
This approach uses the re.findall() function to find all pairs of consecutive words in the string, and a list comprehension to convert the resulting list of strings into a list of tuples.
Python3
import re
test_string = "GFG is best Computer Science Portal"
print ( "The original string : " + str (test_string))
matches = re.findall(r '\b(\w+)\b \b(\w+)\b' , test_string)
res = [(match[ 0 ], match[ 1 ]) for match in matches]
print ( "List after String to tuple conversion : " + str (res))
|
Output
The original string : GFG is best Computer Science Portal
List after String to tuple conversion : [('GFG', 'is'), ('best', 'Computer'), ('Science', 'Portal')]
Time complexity: O(n)
Auxiliary space: O(n)
Method#4: using a list comprehension
Algorithm:
- Initialize a string variable containing a sentence.
- Split the sentence into a list of words using the split() method and store it in a variable.
- Using a list comprehension, create a list of tuples by iterating over the range of indices in the list with a step of 2, and storing a tuple containing the word at the current index and the word at the next index in the list.
- Print the resulting list of tuples.
Python3
test_string = "GFG is best Computer Science Portal"
print ( "The original string : " + str (test_string))
temp = test_string.split()
res = [(temp[i], temp[i + 1 ]) for i in range ( 0 , len (temp), 2 )]
print ( "List after String to tuple conversion : " + str (res))
|
Output
The original string : GFG is best Computer Science Portal
List after String to tuple conversion : [('GFG', 'is'), ('best', 'Computer'), ('Science', 'Portal')]
Time Complexity: O(n), where n is the length of the input string. This is because splitting the string into a list takes O(n) time, and iterating over the list to create tuples takes O(n) time.
Auxiliary Space: O(n), where n is the length of the input string. This is because the list of tuples created takes O(n) space.
Method #5: Using a for loop and enumerate()
Steps:
- Split the string into a list of words using the split() method.
- Create an empty list to store the tuples.
- Loop through the list of words using the enumerate() function to get the index and the word.
- Check if the index is even using the modulus operator %.
- If the index is even, append a tuple to the result list with the current word and the next word in the list.
- Print the result.
Python3
test_string = "GFG is best Computer Science Portal"
print ( "The original string : " + str (test_string))
temp = test_string.split()
res = []
for i, word in enumerate (temp):
if i % 2 = = 0 :
res.append((word, temp[i + 1 ]))
print ( "List after String to tuple conversion : " + str (res))
|
Output
The original string : GFG is best Computer Science Portal
List after String to tuple conversion : [('GFG', 'is'), ('best', 'Computer'), ('Science', 'Portal')]
Time complexity: O(n), where n is the number of words in the string.
Auxiliary space: O(n/2), as the output list contains half the number of elements in the input list.
Method #7: Using itertools.islice() and zip() function
In this method, we use itertools.islice() and zip() function to convert the string to a list of tuples.
Steps:
- Split the string into a list of words using the split() function.
- Use itertools.islice() function to create two iterators, one starting at the first index of the list and incrementing by 2, and the other starting at the second index and incrementing by 2.
- Use zip() function to iterate over both the iterators simultaneously, and create a new list of tuples by combining the current element of the first iterator with the current element of the second iterator.
- Return the new list of tuples.
Python3
import itertools
test_string = "GFG is best Computer Science Portal"
print ( "The original string : " + str (test_string))
temp = test_string.split()
it1 = itertools.islice(temp, 0 , None , 2 )
it2 = itertools.islice(temp, 1 , None , 2 )
res = list ( zip (it1, it2))
print ( "List after String to tuple conversion : " + str (res))
|
Output
The original string : GFG is best Computer Science Portal
List after String to tuple conversion : [('GFG', 'is'), ('best', 'Computer'), ('Science', 'Portal')]
Time complexity: O(n), where n is the number of words in the input string.
Auxiliary space: O(n), where n is the number of words in the input string.
Method#8: Using Recursive method
Algorithm:
- Define a function string_to_tuples that takes a string as its argument.
- Split the string into a list of words using the `split()` method.
- Define a helper function that takes a list as its argument.
- If the length of the list is less than 2, return the result list.
- Otherwise, append a tuple containing the first and second elements of the list to the result list.
- Recursively call the helper function with the remaining elements of the list starting from index 2.
- Return the result list.
Python3
def string_to_tuples(test_string):
temp = test_string.split()
res = []
def helper(lst):
if len (lst) < 2 :
return res
else :
res.append((lst[ 0 ], lst[ 1 ]))
return helper(lst[ 2 :])
return helper(temp)
test_string = "GFG is best Computer Science Portal"
print ( "The original string : " + str (test_string))
res = string_to_tuples(test_string)
print ( "List after String to tuple conversion : " + str (res))
|
Output
The original string : GFG is best Computer Science Portal
List after String to tuple conversion : [('GFG', 'is'), ('best', 'Computer'), ('Science', 'Portal')]
Time Complexity: O(N), where n is the number of words in the input string. This is because the function iterates through the list of words once and each iteration takes constant time.
Auxiliary Space: O(N), where n is the number of words in the input string. This is because the function creates a result list to store the tuples and each tuple takes constant space. The recursive function calls also take up space on the call stack, but since the maximum depth of the call stack is limited by the number of words in the input string.
Last Updated :
11 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...