Best post on tuple operations and immutable tuple- 2

Tuple datatype and tuple operations

Python supports many simple and compound datatypes.

Few data types like list, dictionary are mutable and others like string datatype, tuple are immutable.

Mutable datatypes means changes can be done and are reflected in same variable.

Immutable datatypes means changes can be done but not in same variable.

Tuple is similar to list datatype but only difference between them is that list is mutable and tuple is immutable data type. We can change the contents of list even after assigning values but we cannot change the contents of tuple once assigned with its values.

An empty tuple represents zero or null value.

A tuple datatype can be defined with use of parentheses () containing values separated with comma ” , “.

Each value is termed to be an item of the tuple.

Tuple datatype is Immutable

As we know immutable data type indicates datatypes which are non editable or unchangeable in same variable name.

We cannot modify existing string and so tuples are immutable datatype.

We can create a new tuple with reference to existing or original tuple.

Tuples are immutable - Justified

If we try to change or assign any new value using [ ] operator in existing tuple, we get an error message.

Example:

>>> itv=(1,2,3,4,5,6)
>>> itv[4]=10
Traceback (most recent call last):
File "<pyshell#55>", line 1, in <module>
itv[4]=10
TypeError: 'tuple' object does not support item assignment
>>>

This TypeError: ‘tuple’ object does not support item assignment proves that we cannot modify our existing tuple.

In our case itv holds original tuple and itv[4]=10 tries to edit original string at position 4 with 10

As we receive above message, it becomes clear that tuple datatype cannot update original value and tuples are immutable.

How to deal with immutable tuple?

To remove TypeError while updating tuple, we can create a new tuple based on existing tuple.

Example:

>>> itv=(1,2,3,4,5,6)
>>> itv2=itv+(7,8,9)
>>> itv2
(1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> 

 This example tells us about how to update a tuple with new variable.

In this example concatenation of  tuple slicing is done with  tuple .

According to the location of character which we wish to update we can slice the  tuple and concatenate with required update. 

How to search in a tuple?

We can search a  tuple or letter from a  tuple .

Following example will help us for better understanding :

Example:

def search_a_tuple(itv,item):
for i in range(len(itv)):
if itv[i]==item:
print("match found")
break
else:
print("match not found")

Output:

>>> search_a_tuple((1,2,3,4,5,6),5)
match found
>>> search_a_tuple((1,2,3,4,5,6),15)
match not found
>>>

Tuple Operations

Python supports various tuple operations which helps in performing tasks easily.

Various tuple operations include concatenation, repetition, in operator, not in operator, range and slice operators.

Some of the tuple operations are explained below:

 

tuple operations (itvoyagers.in)

List of tuple operations in python

  • + : Concatenation operator
    • This operator is used to join or merge two tuples together, i.e. values to the either side of + operator will be merged or concatenated.
    • >>> itv=(1,2,3,4,5,6)
      >>> itv2=(10,20,30,40,50,60)
      >>> itv+ itv2
      (1, 2, 3, 4, 5, 6, 10, 20, 30, 40, 50, 60)
  • * : Repetition operator
    • This operator creates new tuple by creating copies of same tuple. 
    • This operator here does not multiply number with tuple but it creates copies of tuple as per specified number.
    • If a single value tuple is defined without trailing comma than it is not considered as tuple it becomes an integer and so it gets multiplied and not repeated
    • >>> itv=(1,2,3,4,5,6)
      >>> itv*2
      (1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6)
      >>> itv1=(8,)
      >>> itv1*4
      (8, 8, 8, 8)
      >>> itv1=(8) #without comma it will be integer not a tuple
      >>> itv1 * 4
      32
      >>>
  • [] : Slice operator
    • This operator is used to get a character from the given string by specifying the index position in [].
    • >>> s='python programming'
      >>> s[6]
      ' '
      >>> s[12]
      'a'
      >>> s[13]
      'm'
  • [:]  : Range Slice operator
    • This operator is used to slice a tuple by specifying start and end position and also an optional parameter of step value.
    • >>> itv=(1,2,3,4,5,6)
      >>> itv[3]
      4
      >>> itv[3:3]
      ()
      >>> itv[3:1:-1]
      (4, 3)
      >>> itv[3:1:-2]
      (4,)
      >>> itv[::]
      (1, 2, 3, 4, 5, 6)
      >>> itv[::-1]
      (6, 5, 4, 3, 2, 1)
      >>>
  • in : Membership operator (in)
    • This operator will return True is character is present in given tuple and False otherwise.
    • >>> itv=(1,2,3,4,5,6)
      >>> 5 in itv
      True
      >>> 7 in itv
      False
  • not in : Membership operator(not in)
    • This operator will return True is character is not present in given tuple and False otherwise.
    • >>> itv=(1,2,3,4,5,6)
      >>> 5 not in itv
      False
      >>> 7 not in itv
      True

Other python related post

Best post on programming language and its types – 1
Python Programming (Basics) – History & Features
Python Programming (Basics)- Debugging & Types of errors
Python Programming (Basics) – Variables, Values, Types & Keywords.
Best post on built-in functions in python – 1
Python Programming (Basics) – Type Conversion
Python Programming (Basics) – Comments,Indentation,Built-in Number Data types and Expressions
Best post on IDLE & script mode in Python – 1
Python Programming (Basics)- Operators in Python
Best post on Order of Operations – Python
Simple and compound statements of python in easy way
Best post on conditional statements in python – Part 1
Best post on conditional statements in python – Part 2
Best post on looping in python (for loop)-Part 1
Best post on looping in python (while loop)-Part 2
Best post on nested loop in python(looping) -Part 3
Best post on infinite loop in python(looping) -Part 4
Best post on control statements(break,continue,pass)-1
Best post on Function definition & calling in python -1
Easy flow of function execution,parameters,arguments-2
Easy fruitful & void function,return values,stack diagrams-3
Best post on types of function arguments in python- 4
Best post on recursive function, scope of variable-5
Best post on import and from statement in python – 1
Best post on modules and built-in modules math,random & time-2
Best post on user defined modules in python-3
Best post on string datatype in python – 1
Best post immutable string,string operations python-2
Best post on string methods in python – 3
Best post on list datatype in python – 1
Best post on mutable list, list operations python – 2
Best post on List methods in python – 3
Best post on dictionary datatype in python – 1
Best post on dictionary methods and operations-2
Best post on tuple datatype in python – 1
Best post on tuple operations and immutable tuple- 2
Best post on tuple methods and built-in functions-3
17 -Python program to demonstrate Button in tkinter and its event in easy way
New posts coming soon…….

Other advance python related post

File Systems and File Handling in Python
Types of file modes and attributes of file object in Python
How to read,write and append in a file in python?
Remaining file methods in Python
File Positions in Python
Directory in Python and its methods
Iterator and Iterables in Python
Exceptions in Python
Exception Handling in Python (Part I)
Exception Handling in Python (Part II)
Regular Expressions
Metacharacters or Regular Expression Patterns
Functions in ‘re’ module(Part I)- Match vs Search
Functions in ‘re’ module(Part II)-findall(), split(), sub()
Flags for regular expressions(Modifiers)
GUI programming in Python and Python GUI Library
What is Tkinter ?
Layout Manager (Geometry Manager) in Python
Events and Bindings in Python along with Widget configuration and styling
Fonts Names, Font Descriptors, System Fonts, Text formatting, Borders, Relief Styles in Python
Best post:Dimensions, Anchors, Bitmaps & Cursors in Python
Canvas widget of tkinter module – Python
Widgets in tkinter module – Python
Label, Text, Entry & Message Widget in Python
Button, Checkbutton & Radiobutton Widget in Python
Best post on Menu and Menubutton Widget of tkinter
Best post- Listbox and Scrollbar(Slider) Widget-Python
Best post on Frame Widget of tkinter in Python
Best post: message box widget and its methods
Best post- LabelFrame, Toplevel, PanedWindow widgets
Best post on Spinbox and Scale Widget in Python
Best post : Database connectivity in Python (Part 1)
Best post : Database Connectivity in Python (Part 2)
Best post on Create and Insert query : Python + MySQL
Best post on Select Query to Search & Read: Python + MySQL-4
Best post on Update query and Delete query : Python + MySQL-4
New posts coming soon…….
We are aiming to explain all concepts of Python in easiest terms as possible.
ITVoyagers-logo
ITVoyagers
Author

Leave a Comment