Tuple Functions in Python

Python tuple ()

The tuple () builtin can be used to produce tuples in Python.

In Python, a tuple is an inflexible sequence type. One of the ways of creating tuple is by using the tuple () construct.




The syntax of tuple () is

tuple (iterable)

tuple () Parameters

iterable ( voluntary)-an iterable (list, range,etc.) or an iterator object
Still, the function returns an empty tuple, If the iterable isn't passed to tuple ().
Illustration Produce tuples using tuple ()
t1 = tuple ()
print ('t1 = ', t1)
.# creating a tuple from a list
t2 = tuple ( (1, 4, 6))
print ('t2 = ', t2)
.# creating a tuple from a string
t1 = tuple ('Python')
print ('t1 = ', t1)
.# creating a tuple from a wordbook
t1 = tuple ( 1'one', 2'two')
print ('t1 = ', t1)
Affair


t1 = ()
t2 = (1, 4, 6)
. t1 = ('P','y','t','h','o','n')
.t1 = (1, 2)

A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The main difference between the tuples and the lists is that the tuples cannot be changed unlike lists. Tuples use parentheses, whereas lists use square brackets.

Creating a tuple is as simple as putting different comma-separated values. Optionally, you can put these comma-separated values between parentheses also. For example −

tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5 )
tup3 = "a", "b", "c", "d"

The empty tuple is written as two parentheses containing nothing −

tup1 = ();

To write a tuple containing a single value you have to include a comma, even though there is only one value −

tup1 = (50,)

Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.

Accessing Values in Tuples

To access values in tuple, use the square brackets for slicing along with the index or indices to obtain the value available at that index. For example −

Live Demo
#!/usr/bin/python3

tup1 = ('physics', 'chemistry', 1997, 2000)
tup2 = (1, 2, 3, 4, 5, 6, 7 )

print ("tup1[0]: ", tup1[0])
print ("tup2[1:5]: ", tup2[1:5])

When the above code is executed, it produces the following result −

tup1[0]:  physics
tup2[1:5]:  (2, 3, 4, 5)
Insideaiml is a platform where you can learn AI & ML perfectly and get certified.

Comments

Popular posts from this blog

Tanh Activation Function

Sigmoid Activation Function And Its Uses.

Unleashing Creativity: The Latest Frontier of Animation AI