Python Tuple

Python Tuple:
A tuple is a collection of items which are in order and unchangeable which means that tuple are immutable.
In Python tuple are written with round brackets.

Example:

tuple1 = ("pen""book""copy")
print(tuple1)

Output:
("pen""book""copy")

Accessing tuple Items:

You can access tuple items by selecting the index number, inside square brackets.

Example:

tuple1 = ("pen""book""copy")
print(tuple1[2])

Output:
"copy"

Note:Once a tuple is created, we cannot change its values they are unchangeable.

Checking of Item in tuple:

in keyword is used to check the item in tuple.

Example:

tuple1 = ("pen""book""copy")
if "pen" in tuple1:
  print("Yes, 'pen' is in the tuple")

Output:
Yes, 'pen' is in the tuple

for loop through a tuple:

Example:

tuple1 = ("pen""book""copy")
for x in tuple1:
  print(x)

Output:
pen
book
copy

count( ) method in tuple:

count() method returns the number of times a value appears in the tuple.

Example:

tuple1 = (23787, 74, 385)
x = tuple1.count(7)
print(x)

Output:
3

Length of tuple:

Use the len() method.

Example:

tuple1 = ("pen""book""copy")
print(len(tuple1))

Output:
3

index( ) method in tuple:

index() method finds the position of the specified value.

Example:

tuple1 = (2378774385)
x = tuple1.index(7)
print(x)

Output:
2

Note: In above example,the output we get is 2 which is of 7 which occur first.

tuple( ) constructor:

Use the tuple() constructor to make a tuple.

Example:

tuple1 = tuple(("pen""book""copy"))
print(tuple1)

Output:
("pen""book""copy")


Some important points for tuple:

  1. We cannot use add( ) method for tuple as tuple is immutable.
  2. We cannot use remove( ) or del method for tuple as tuple is immutable.

Post a Comment

0 Comments