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'
Tuples are immutable i.e we can't change the elements.

However we can use + operator to add element but that will create a new tuple. We can check this by using id() . After adding we will get new id for the tuple ( object )
my_tuple=(5,7,5,4,3,5) 
print(id(my_tuple)) # 139787173397704
my_tuple +=(9,8)
print(id(my_tuple)) # 139787174601112
print(my_tuple)     #(5, 7, 5, 4, 3, 5, 9, 8)

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




plus2net.com



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