Thursday, 4 April 2024

Python Tuples

 

Tuples


A tuple is an ordered sequence of items same as a list. The only difference is that tuples are immutable. Tuples once created cannot be modified.

Tuples are used to write-protect data and are usually faster than lists as they cannot change dynamically.

It is defined within parentheses () where items are separated by commas.


Program:

subjects=('DS','MCWC','ML','DBMS')

print(subjects)

# Scripts Ends 

Output:

('DS', 'MCWC', 'ML', 'DBMS')


A. Accessing and Slicing a Tuple

You access a tuple the same way as you’d access a list. The same goes for slicing it.

Program:

subjects=('DS','MCWC','ML','DBMS')

print(subjects[1])

print(subjects[0:2])

# Scripts Ends 

Output:

'MCWC'

('DS', 'MCWC')


B. A tuple is Immutable

Python tuple is immutable. Once declared, you can’t change its size or elements.

Program:

subjects=('DS','MCWC','ML','DBMS')

subjects[2]='Biology'

print(subjects)

# Scripts Ends 

Output:

TypeError: 'tuple' object does not support item assignment


No comments:

Post a Comment

Interactive Report: Introduction to the Internet of Things (IoT) ...

Popular Posts