Python tuple() function
The tuple() function in Python returns a tuple object. Basically, this function is used to create tuples in Python. For example:
x = [12, 32, 543] y = tuple(x) print(type(y)) a = tuple([12, 43, 453]) print(type(a)) b = tuple(["codes", "cracker", "dot", "com"]) print(type(b))
The output is:
<class 'tuple'> <class 'tuple'> <class 'tuple'>
Note: To learn in detail about tuples, refer to their separate post.
Python tuple() function syntax
The syntax of the tuple() function in Python is:
The iterable parameter is optional. Means that if no iterable is specified, tuple() returns a tuple object, of course, but an empty tuple. An iterable may be a list, dictionary, etc.
Note: When a dictionary is used as an iterable, then its key will be used.
Python tuple() function example
Here is an example of the tuple() function in Python:
x = [1, 2, 3, 5] a = tuple(x) print(a) x = "Python Programming" a = tuple(x) print(a) x = {"Day": "Sun", "Month": "Dec"} a = tuple(x) print(a)
The output is:
(1, 2, 3, 5)
('P', 'y', 't', 'h', 'o', 'n', ' ', 'P', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g')
('Day', 'Month')
Advantages of the tuple() function in Python
- Tuples are immutable, which means that once created, their values cannot be altered. This is useful in situations where data integrity is essential.
- Tuples are more memory efficient than lists because they require less overhead and can be stored in a more compact manner.
- As their elements are stored in contiguous memory locations, tuples can be iterated over faster than lists.
Disadvantages of the tuple() function in Python
- Comparatively speaking, tuples are less functional than lists. They lack techniques for introducing, eliminating, or changing elements.
- Tuples cannot have their values changed and can only be accessed through indexing. In situations where dynamic data manipulation is necessary, this can be problematic.
- In situations where the data structure must be changed frequently or dynamically, tuples are inappropriate. They work best in situations where the data is set in stone or read-only.
« Previous Function Next Function »
Liked this post? Share it!