You are on page 1of 4

12/30/21, 12:06 PM 4.

Tuple

Tuples

A tuple is Similiar to List

The diffence diffence between the two is that we can't change the elements of tuple we can't
change the elements of tuple once it is assigned whereas in the list, elements can be changed

Tuple is immutable

Tuples use parentheses parentheses, whereas lists use square brackets.

In [2]:
t1 = (1,2,"hello",True)

In [3]:
t1

Out[3]: (1, 2, 'hello', True)

In [3]:
# Access Tuple Items with Index Numbering

t1[1]

Out[3]: 2

In [4]:
# Negative Indexing refers the index from last item

t1[-1]

Out[4]: True

In [6]:
# Range of Indexes

t1[1:4]

Out[6]: (2, 'hello', True)

In [8]:
# Range of Negative Index

t1[-4:-1]

Out[8]: (1, 2, 'hello')

In [4]:
# length of Tuple

len(t1)

Out[4]: 4

In [6]:
# To Add items

t1 = (1,2,"hello",True)

file:///C:/Users/rgandyala/Downloads/4. Tuple.html 1/4


12/30/21, 12:06 PM 4. Tuple

t1

Out[6]: (1, 2, 'hello', True)

In [7]:
t1[3] = False

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

<ipython-input-7-c7dfc71f5c9d> in <module>

----> 1 t1[3] = False

TypeError: 'tuple' object does not support item assignment

In [8]:
# To remove the Tuple

del t1

In [9]:
# Joining twot Tuples

t1 = (1,2,"hello",True)

t2 =(False,"world")

In [6]:
t3 = t1+t2

In [7]:
t3

Out[7]: (1, 2, 'hello', True, False, 'world')

In [8]:
# Count - Number of times a word is getting repeated

t3.count(2)

Out[8]: 1

In [23]:
# to find the index number of Item in the tuple

t3.index("hello")

Out[23]: 2

In [11]:
# tuple with one value end with Comma

t4 = (2,)

In [12]:
t4

Out[12]: (2,)

file:///C:/Users/rgandyala/Downloads/4. Tuple.html 2/4


12/30/21, 12:06 PM 4. Tuple

In [13]: # Nested Tuple

# create a tuple with one value and one tuple and one list

t5 = (1, (2, 3, 4), [1, "hello","world", 28, 'abc'])

In [14]:
t5

Out[14]: (1, (2, 3, 4), [1, 'hello', 'world', 28, 'abc'])

In [17]:
# Repeat the elements in a tuple for a given number of times using the * operator.

t6 = (("hello",)* 4)

In [18]:
t6

Out[18]: ('hello', 'hello', 'hello', 'hello')

In [19]:
# Tuple Sort

t7 = (3,2,1,4,6,5)

In [20]:
t8 = sorted(t7)

In [21]:
t8

Out[21]: [1, 2, 3, 4, 5, 6]

In [22]:
# Largest Elements

max(t8)

Out[22]: 6

In [23]:
# Smallest Elements

min(t8)

Out[23]: 1

In [24]:
# using tuple we can create for loops

t =(1,2,3,4,5)

print('tuple')

for x in t:

print(x)

tuple

file:///C:/Users/rgandyala/Downloads/4. Tuple.html 3/4


12/30/21, 12:06 PM 4. Tuple

In [ ]:

file:///C:/Users/rgandyala/Downloads/4. Tuple.html 4/4

You might also like