Tuple In Python | How to use tuple in python | Python Tuples

Tuple In Python

tuple in python


A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the items of different data types. The items of the tuple are separated with a comma (,) and enclosed in parentheses (). A tuple is a read-only data structure as we can't modify the size and value of the items of a tuple.

Example:

tuple = ( 'abc'123 , 'hi'10.12 , 10 )
print (tuple)
print (tuple[0])
print (tuple[2:4])
print (tuple[3:])
print (tuple * 2)
print (tuple + tuple)

Output:

('abc'123'hi'10.1210)
abc
('hi'10.12)
(10.1210)
('abc'123'hi'10.1210'abc'123'hi'10.1210)
('abc'123'hi'10.1210'abc'123'hi'10.1210)



Accessing Tuple 

Accessing the tuple is pretty easy, we can access tuple in the same way as List.

Example:

tuple = ( 'abc'123 , 'hi'10.12 ,10 )
print (tuple[0])
print (tuple[2:4])
print (tuple[3:])
print (tuple[-3:-1])

Output:

abc
('hi'10.12)
(10.1210)
('hi'10.12)



Adding Tuples 

Tuple can be added by using the concatenation operator(+) to join two tuples.

Example:

tuple = ( 'abc'123 )
tuple1 = ('hi'10.12 , 10)
print (tuple+tuple1 )

Output:

('abc'123'hi'10.1210)



Replicating Tuple 

Replicating means repeating. It can be performed by using '*' operator by a specific number of times.

Example:

tuple = ( 'abc'123 )
print (tuple*2)

Output:

('abc'123'abc'123)



Tuple Slicing 

A subpart of a tuple can be retrieved on the basis of an index. This subpart is known as tuple slice. 

Example:

tuple = ( 'abc'123 , 'hi'10.12 , 10 )
print (tuple[0])
print (tuple[2:4])
print (tuple[3:])
print (tuple[-3:-1])

Output:

abc
('hi'10.12)
(10.1210)
('hi'10.12)


Tuple Deleting 

Deleting individual elements from a tuple is not supported. However, the whole of the tuple can be deleted using the del statement. 

Example:

tuple = ( 'abc'123 , 'hi'10.12 , 10 )
print (tuple)
del tuple
print (tuple)

Output:

('abc'123'hi'10.1210)
<class 'tuple'>



min(tuple) Method 

This method is used to get min value from the sequence of tuple.

Example:

tuple = ( 123 , 10.12 , 10 )
print (min(tuple))

Output:

10



max(tuple) Method 

This method is used to get the max value from the sequence of tuple.

Example:

tuple = ( 123 , 10.12 , 10 )
print (max(tuple))

Output:

123



len(tuple) Method 

This method is used to get the length of the tuple. 

Example:

tuple = ( 123 , 10.12 , 10 )
print (len(tuple))

Output:

3
Next Post Previous Post
No Comment
Add Comment
comment url