Sunday 20 October 2019

Python Tuple

Python Tuple


Tuple is an ordered sequence of items. Tuple in python are very similar to  List. The only difference between Tuple and List is that tuples are immutable. Values cannot be modified in Tuples once created.

Tuples are used to create a data which we don't want to change after it's creation. Values inside tuples are like protected data and are usually faster than list as it cannot change dynamically.

Tuples are defined using parentheses (). Items inside tuples are separated by commas. Example of tuple is shown below:


>>> myTuple = (101,'PythonPracticals', 'KPatel')
>>> print(myTuple)
(101, 'PythonPracticals', 'KPatel')


We can refer individual elements of Tuple as shown below:

>>> print(myTuple[0])
101

We can use the slicing operator [ ] to extract items from Tuple but we cannot change its value. For example:


# Using Slicing Operator with Tuple

>>> print(myTuple[0:2])
(101,'PythonPracticals')

# Editing value of Tuple

>>> myTuple[0]=105
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    myTuple[0]=105
TypeError: 'tuple' object does not support item assignment




* * * * *

< Back to Home Page >

No comments:

Post a Comment