Create a tuple from string and list – Python
The task of creating a tuple from a string and a list in Python involves combining elements from both data types into a single tuple. The list elements are added as individual items and the string is treated as a single element within the tuple. For example, given a = [“gfg”, “is”] and b = “best”, the goal is to create the tuple (‘gfg’, ‘is’, ‘best’).
Using + operator
+ operator is an efficient way to create a tuple from a list and a string . It works by concatenating two tuples, the list is first converted to a tuple and the string is wrapped in a single-element tuple (b,). It is preferred for its simplicity when combining fixed elements into a new tuple.
a = ["gfg", "is"] # list
b = "best" # string
res = tuple(a) + (b,)
print(res)
Output
('gfg', 'is', 'best')
Explanation: tuple(a) + (b,) converts the list a into a tuple and wraps the string b in a single-element tuple. Since tuples can only be concatenated with other tuples, the + operator combines them into (‘gfg’, ‘is’, ‘best’).
Table of Content
Using * operator
* operator, known as iterable unpacking, is a modern way to create a tuple from a list and a string . It works by unpacking the elements of the list into a tuple alongside the string. This approach is particularly concise, often favored for combining multiple elements into a tuple without converting types explicitly.
a = ["gfg", "is"] # list
b = "best" # string
res = (*a, b)
print(res)
Output
('gfg', 'is', 'best')
Explanation: (*a, b) unpacks the list a into individual elements and places them in a new tuple, followed by the string b as the last element.
Using chain()
chain() from the itertools module is a powerful method for combining multiple iterables like lists and strings into a single sequence. It efficiently iterates over each element in sequence without creating intermediate lists, making it suitable for creating large tuples from diverse data sources.
from itertools import chain
a = ["gfg", "is"] # list
b = "best" # string
res = tuple(chain(a, [b]))
print(res)
Output
('gfg', 'is', 'best')
Explanation: tuple(chain(a, [b])) uses chain() from the itertools module to iterate over the list a and a single-element list [b] as if they were a single sequence.
Using append()
append() is a simple and direct approach when combining a string into an existing list before converting it to a tuple. This method modifies the original list by appending the string, after which the list is converted into a tuple. While easy to understand, it is less flexible as it alters the input list.
a = ["gfg", "is"] # list
b = "best" # string
a.append(b)
res = tuple(a)
print(res)
Output
('gfg', 'is', 'best')
Explanation: a.append(b) adds the string b to the end of the list a and tuple(a) then converts this updated list into a tuple.