Creating a Tuple
Creating a tuple in Python can be accomplished using parentheses ()
or the tuple()
constructor. Tuples can contain elements of different data types and are defined by enclosing elements within parentheses and separating them with commas.
Using Parentheses ()
You can create a tuple by directly assigning values within parentheses.
Example:
my_tuple = (1, 2, 'hello', 3.5)
Using tuple()
Constructor
The tuple()
constructor can create a tuple from an iterable, such as a list or a string.
Example:
list_items = [1, 2, 3]
tuple_from_list = tuple(list_items)
string_data = 'hello'
tuple_from_string = tuple(string_data)
Tuple with Single Element
When creating a tuple with a single element, include a comma after the element to differentiate it from the expression within parentheses. This distinguishes it as a tuple rather than a parenthesized expression.
Example:
single_element_tuple = (5,) # Tuple with a single element 5