![]() |
VOOZH | about |
In Python, tuple() is a built-in function also known as tuple constructor, used to create a tuple from an iterable such as a list, string or range. A tuple is an ordered and immutable sequence type. For Example:
(1, 2, 3)
tuple(iterable)
Parameter: iterable (optional) - Any iterable object such as list, string, set, range or iterator.
This code shows how the tuple() function behaves with different inputs. It creates an empty tuple when no value is passed and converts other iterables like lists and strings into tuples.
Empty Tuple: ()
List to Tuple: (1, 2, 3, 4)
String to Tuple: ('g', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's')
This example shows what happens when you pass a non-iterable value to tuple(). Since integers are not iterable, Python raises a TypeError.
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 1, in <module>
TypeError: 'int' object is not iterable
This example creates a tuple and retrieves a slice of elements using index positions. Tuple slicing works the same way as lists.
(2, 3, 4)
Explanation:
This example shows what happens when a tuple is deleted using del. After deletion, trying to access the tuple again causes an error because it no longer exists in memory.
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 3, in <module>
NameError: name 't' is not defined
Explanation:
This example shows how to convert a dictionary into a tuple. The items() method returns key–value pairs and tuple() converts them into a tuple of pairs.
(('apple', 1), ('banana', 2), ('cherry', 3))
Explanation:
1. len():len() function returns the total number of items present in a tuple. It helps you quickly check how many elements the tuple contains.
3
2. max():max() function returns the largest value from the tuple. This works only when all elements are comparable (numbers, characters, etc.).
3
3. min():min() function returns the smallest value from the tuple. Like max(), this works when the tuple contains comparable data.
1
4. sum():sum() function adds all the numeric elements in the tuple and returns the total. It works only for tuples containing numbers.
6
5. sorted():sorted() function sorts the elements of the tuple in ascending order and returns a new list. If you want the result as a tuple, you can convert the list back into a tuple.
(1, 2, 3)
Python supports both tuples and lists as data structures that may be used to hold a collection of data. Nevertheless, there are certain benefits to utilising tuples rather than lists.