Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python 04uple

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Tuple

A tuple is a collection which is ordered and unchangeable. In Python tuples


are written with round brackets.

Create a tuple

thistuple = ("apple", "banana", "cherry")


print(thistuple)

Output :

('apple', 'banana', 'cherry')

NOTE:- Indexing of tuple is just similar to indexing of list

Access Tuple Items

You can access tuple items by referring to the index number, inside square
brackets:

Return the item in position 1:

thistuple = ("apple", "banana", "cherry")


print(thistuple[1]) # returns banana

print ("thistuple[1:2]: ",thistuple[1:2]) # returns banana cherry

Output :
Change Tuple Values

Once a tuple is created, you cannot change its values. Tuples


are unchangeable.

Example

You cannot change values in a tuple:

thistuple = ("apple", "banana", "cherry")


thistuple[1] = "blackcurrant"

Python Chapter-04 Page 1


# The values will remain the same:
print(thistuple)

Loop Through a Tuple

You can loop through the tuple items by using a for loop.

Iterate through the items and print the values:

thistuple = ("apple", "banana", "cherry")


for x in thistuple:
print(x)

Output :

apple

banana

cherry

Check if Item Exists

To determine if a specified item is present in a tuple use the in keyword:

Check if "apple" is present in the tuple:

thistuple = ("apple", "banana", "cherry")


if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")

Output :

Yes, 'apple' is in the fruits tuple

Add Items

Once a tuple is created, you cannot add items to it. Tuples


are unchangeable.

You cannot add items to a tuple:

thistuple = ("apple", "banana", "cherry")


thistuple[3] = "orange" # This will raise an error
print(thistuple)

Python Chapter-04 Page 2


Remove Items

Note: You cannot remove items in a tuple.

Tuples are unchangeable, so you cannot remove items from it, but you can
delete the tuple completely:

The del keyword can delete the tuple completely:

thistuple = ("apple", "banana", "cherry")


del thistuple
print(thistuple) #this will raise an error because the tuple no
longer exists

Adding two tuples

Tuples are immutable,that’s why we can’t change the content of tuple.It’s alternate way is to
take contents of existing tuple and create another tuple with these contents as well as new
content.

E.g. tup1 = (1, 2)

tup2 = ('a', 'b')

tup3 = tup1 + tup2

print (tup3)

Output (1, 2, 'a', 'b')

Delete Tuple Elements

Direct deletion of tuple element is not possible but shifting of required content after discard of
unwanted content to another tuple.

e.g. tup1 = (1, 2,3)

tup3 = tup1[0:1] + tup1[2:]

print (tup3)

Output (1, 3)

Tuple Methods

Python Chapter-04 Page 3


Python has two built-in methods that you can use on tuples.

(a) Count – Returns the number of times a specified value occurs in a tuple

thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.count(5)
print(x)

Output : 2

(b) index - Searches the tuple for a specified value and returns the position
of where it was found.

Search for the first occurrence of the value 8, and return its position:

thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = thistuple.index(8)
print(x)

Output : 3

(c) len () - To determine how many items a tuple has, use


the len() method:

Print the number of items in the tuple:

thistuple = ("apple", "banana", "cherry")


print(len(thistuple))

Output : 3

(d) max - returns the maximum element in a tuple

Example:

Tuple = (456,700,200)

Print (“maximum value “, max(tuple))

(e) min - returns the minimum element in a tuple

Example:

Tuple = (456,700,200)

Print (“minimum value “, min(tuple))

Search an element in tuple without using membership operator

Python Chapter-04 Page 4


thistuple = ("apple", "banana", "cherry")
l = len(thistuple)
f = 1
for x in range(l):
if thistuple[x] == "cherry":
f = 1
if f ==1 :
print("Yes, 'apple' is in the fruits tuple")
else:
print("No, 'apple' is in the fruits tuple")

Adding element in tuple using List

Python tuple is an immutable object. Hence any operation that tries to modify it (like append) is not allowed.
However, following workaround can be used.

First, convert tuple to list by built-in function list(). You can always append item to list object. Then use
another built-in function tuple() to convert this list object back to tuple.

>>> T1=(10,50,20,9,40,25,60,30,1,56)

>>> L1=list(T1)

>>> L1

[10, 50, 20, 9, 40, 25, 60, 30, 1, 56]

>>> L1.append(100)

>>> T1=tuple(L1)

>>> T1

(10, 50, 20, 9, 40, 25, 60, 30, 1, 56, 100)

You can see new element appended to original tuple representation.

Exercises

1. Write a Python program to create a tuple.

2. Write a Python program to create a tuple with different data types.

3. Write a Python program to create a tuple with numbers and print one item.

4. Write a Python program to add an item in a tuple.

5. Write a Python program to get the 4th element and 4th element from last of a tuple.

6. Write a Python program to find the repeated items of a tuple.

7. Write a Python program to check whether an element exists within a tuple.

8. Write a Python program to convert a list to a tuple.

9. Write a Python program to remove an item from a tuple.

Python Chapter-04 Page 5


10. Write a Python program to slice a tuple.

11. Write a Python program to find the index of an item of a tuple.

12. Write a Python program to find the length of a tuple.

13. Write a Python program to reverse a tuple.

14. Write a Python program to sort a tuple .

Practice questions

1. What is the output of print tuple * 2 if tuple = (123, ‘FREYA’)?

2. What Will Be The Output Of The Following Code Snippet?


tuple_a = 1, 2
tuple_b = ('3', '4')
print (tuple_a + tuple_b)
3. What Will Be The Output Of The Following Code Snippet?
tuple_a = 1, 2
tuple_b = (3, 4)
r=[sum(x) for x in [tuple_a + tuple_b]]
print(r)
4. Which Of The Following Statements Given Below Is/Are True?
A. Tuples have structure, lists have an order.
B. Tuples are homogeneous, lists are heterogeneous.
C. Tuples are immutable, lists are mutable.
D. All of them.
5. What Will Be The Output Of The Following Code Snippet?
tuple = ('Python') * 4
print(type(tuple))
6. What Will Be The Output Of The Following Code Snippet?
tuple = (1,) * 3
tuple[0] = 2
print(tuple)
7. What will be the output?
t=(11,121,14,13)
print(t[1:3])
8. What will be the output?
t = (11, 12, 14, 13, 18, 19)
r=[t[i] for i in range(0, len(t), 2)]
print(r)
9. What will be the output?
t1 = (1, 2, 3, 3)
t2 = (1, 2, 3, 4)
print(t1 < t2)

Python Chapter-04 Page 6


10. What will be the output?
a=(2,3,4)
print( sum(a,3))
11. What is the output of the following piece of code?
a=(0,1,2,3,4)
b=slice(0,2)
print(a[b])
12. How we can compare items of two tuples?

Python Chapter-04 Page 7

You might also like