tuple in Python

Declaring a tuple

my_tuple=('Alex','Ronald','John')
print(my_tuple)
Output
('Alex', 'Ronald', 'John')
Displaying elements based on position
my_tuple=("Alex","Ronald","John")
print(my_tuple[1])
Output is here
Ronald
The position starts from 0 and first element value is my_tuple[0], so the data at my_tuple[1] gives us Ronald.

Displaying all items by looping

We used for loop to display all items of the tuple.
my_tuple=('Alex','Ronald','John')
for i in my_tuple:
    print(i)
Output is here
Alex
Ronald
John

Add , remove , update elements

We can't add or remove elements of tuple. There is no append object in tuple
AttributeError: 'tuple' object has no attribute 'append'

Searching element

my_tuple=('Alex','Ronald','John')
if 'Ronald' in my_tuple:
 print("Yes, Present in Tuple")
else:
 print("No , not present in Tuple")
Output is here
Yes, Present in Tuple

Number of elements in the tuple

my_tuple=('Alex','Ronald','John')
print("Number of elements: ",len(my_tuple))
Output is here
Number of elements: 3

Deleting tuple

my_tuple=('Alex','Ronald','John')
del my_tuple
print("Number of elements: ",len(my_tuple))
The last line will create error as we are deleting the tuple before this line.

Number of occurrence

count()
my_tuple=(5,7,5,4,3,5)
print ("Number of times 5 is : ",my_tuple.count(5) )
Output is here
Number of times 5 is :  3

Position of element

index()
my_tuple=(5,7,5,4,3,5)
print ("Position of 3 is  : ",my_tuple.index(3) )
Output
Position of 3 is  :  4


Your Rating




Post your comments , suggestion , error , requirements etc here




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2019 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer