Open In App

Python | Convert String to list of tuples

Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate working of
# Convert String to list of tuples
# Using zip() + list slicing + split()
 
# Initialize string
test_string = "GFG is best Computer Science Portal"
 
# Printing original string
print("The original string : " + str(test_string))
 
# Convert String to list of tuples
# Using zip() + list slicing + split()
temp = test_string.split()
res = list(zip(temp[::2], temp[1::2]))
 
# Printing result
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




# Python3 code to demonstrate working of
# Convert String to list of tuples
# Using iter() + split() + next() + generator expression
 
# Initialize string
test_string = "GFG is best Computer Science Portal"
 
# Printing original string
print("The original string : " + str(test_string))
 
# Convert String to list of tuples
# using iter() + split() + next() + generator expression
temp = iter(test_string.split())
res = [(ele, next(temp)) for ele in temp]
 
# Printing result
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
 
# Initialize string
test_string = "GFG is best Computer Science Portal"
 
# Printing original string
print("The original string : " + str(test_string))
 
# Convert String to list of tuples
# using re.findall() and list comprehension
matches = re.findall(r'\b(\w+)\b \b(\w+)\b', test_string)
res = [(match[0], match[1]) for match in matches]
 
# Printing result
print("List after String to tuple conversion : " + str(res))
 
# This code is contributed by Edula Vinay Kumar Reddy


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:

  1. Initialize a string variable containing a sentence.
  2. Split the sentence into a list of words using the split() method and store it in a variable.
  3. 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.
  4. Print the resulting list of tuples.

Python3




# Initialize string
test_string = "GFG is best Computer Science Portal"
 
# Printing original string
print("The original string : " + str(test_string))
 
# Convert String to list of tuples
# using list comprehension + zip()
temp = test_string.split()
res = [(temp[i], temp[i+1]) for i in range(0, len(temp), 2)]
 
# Printing result
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:

  1. Split the string into a list of words using the split() method.
  2. Create an empty list to store the tuples.
  3. Loop through the list of words using the enumerate() function to get the index and the word.
  4. Check if the index is even using the modulus operator %.
  5. If the index is even, append a tuple to the result list with the current word and the next word in the list.
  6. Print the result.

Python3




# Initialize string
test_string = "GFG is best Computer Science Portal"
 
# Printing original string
print("The original string : " + str(test_string))
 
# Convert String to list of tuples
# using a for loop and enumerate()
temp = test_string.split()
 
# Empty list
res = []
 
for i, word in enumerate(temp):
    if i % 2 == 0:
        res.append((word, temp[i+1]))
 
# Printing result
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:

  1. Split the string into a list of words using the split() function.
  2. 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.
  3. 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.
  4. Return the new list of tuples.

Python3




import itertools
 
# Initialize string
test_string = "GFG is best Computer Science Portal"
 
# Printing original string
print("The original string : " + str(test_string))
 
# Convert String to list of tuples
# using itertools.islice() and zip() function
temp = test_string.split()
 
it1 = itertools.islice(temp, 0, None, 2)
it2 = itertools.islice(temp, 1, None, 2)
 
res = list(zip(it1, it2))
 
# Printing result
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:

  1. Define a function string_to_tuples that takes a string as its argument.
  2. Split the string into a list of words using the `split()` method.
  3. Define a helper function that takes a list as its argument.
  4. If the length of the list is less than 2, return the result list.
  5. Otherwise, append a tuple containing the first and second elements of the list to the result list.
  6. Recursively call the helper function with the remaining elements of the list starting from index 2.
  7. Return the result list.

Python3




# Function
# To convert string to tuples
 
 
def string_to_tuples(test_string):
    temp = test_string.split()
 
    # Empty list
    res = []
 
    # heper function
    def helper(lst):
 
        if len(lst) < 2:
            return res
        else:
            res.append((lst[0], lst[1]))
            return helper(lst[2:])
 
    return helper(temp)
 
 
# Initialize string
test_string = "GFG is best Computer Science Portal"
 
# Printing original string
print("The original string : " + str(test_string))
 
# Convert String to list of tuples using recursive method
res = string_to_tuples(test_string)
 
# Printing result
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
Previous
Next
Share your thoughts in the comments
Similar Reads