About Python tuple
In Python, a tuple is a collection of ordered elements.
Tuple is immutable which means that its elements cannot be changed after the tuple is created.
Tuple can contain items of different data types.
In Python, tuple items are placed inside parentheses '()' and items are separated with commas.
Creating a tuple in Python
Using parentheses ():
1. Create a collection of string (collection of fruit names like "Apple", "Banana", "Cherry", "Orange") separated by commas (,) and place them inside parentheses '()'. The code will look like this: ("Apple", "Banana", "Cherry", "Orange")
. A tuple is created.
2. Create a variable name fruit_tuple
and assign the tuple of string to the fruit_tuple variable. Use print() function to print the tuple.
Please take a closer look at the following example:
Example of creating tuple
Output of the above example
The fruit tuple is: ('Apple', 'Banana', 'Cherry', 'Orange')
Using the tuple() constructor:
You can create a tuple by passing an iterable like a string, set, or list to the tuple() constructor.
Tuple from string:
1. Create a string "Python"
and pass it inside tuple() constructor like this - tuple("Python")
. It will create a tuple of char.
2. Create a variable name char_tuple
and assign the tuple to the char_tuple variable. Use print() function to print the tuple.
Tuple from list:
1. Create a list [1, 2, 3, 4]
and pass it to the tuple() constructor like this - tuple([1, 2, 3, 4])
. It will create a tuple of integer numbers.
Tuple from set:
1. Create a set {1, 2, 3, 4}
and pass it to the tuple() constructor like this - tuple({1, 2, 3, 4})
. It will create a tuple of integer numbers.
Please take a closer look at the following examples:
Example of creating tuple using tuple() constructor
Output of the above example
The char tuple is: ('P', 'y', 't', 'h', 'o', 'n') tuple from list: (1, 2, 3, 4) tuple from set: (1, 2, 3, 4, 5)