Python built-in Method - tuple()
The tuple()
method is a built-in function in Python that is used to create a tuple object. A tuple is an ordered, immutable sequence of elements, which means that once a tuple is created, it cannot be modified.
Here is the syntax for the tuple()
method:
tuple(iterable)
The iterable
parameter is the object that you want to convert to a tuple. It can be any object that is iterable, such as a list, string, or set.
Here are some examples of using the tuple()
method:
x = [1, 2, 3, 4, 5] t = tuple(x) print(t) # output: (1, 2, 3, 4, 5) s = "hello" t = tuple(s) print(t) # output: ('h', 'e', 'l', 'l', 'o')
In the first example, we create a list x
containing the integers 1 to 5, and then use the tuple()
method to convert the list to a tuple. In the second example, we create a string s
containing the characters "hello", and then use the tuple()
method to convert the string to a tuple of characters.
The tuple()
method is useful when you need to create an ordered sequence of elements that cannot be modified after creation. Tuples are often used to represent a fixed set of values, such as the coordinates of a point in space or the RGB color values of a pixel in an image.