Best post on tuple methods and built-in functions-3

Tuple methods in python

Python supports various compound datatypes like String, tuple,dictionary etc.

In previous post we studied about what are tuples? and tuple operations

A Tuple is a collection of Python objects separated by commas. In someways a tuple is similar to a list in terms of indexing, nested objects and repetition but a tuple is immutable unlike lists which are mutable.

In this post we will be concentrating on various tuple methods.

Tuple consist of various methods for easy functioning and utilization of python script.

Many built-in functions can be used on tuples like min(), max(), len(), sum(), any(), all(), sorted() and tuple().

Apart from this, methods of tuple are count() and index().

List of tuple methods

  • index()
    • This method takes one argument and returns the index of the first appearance of an item in a tuple. We call a method using the dot operator in python.
    • T.index(value)
    • Example:
    • >>> x=(11,22,33,44,55,22,66,77,88,99,22)
      >>> x.index(22)
      1
      >>> x.index(77)
      7
    • Here 22 is present on index 1,5 and 10 but its first occurence is considered.
  •  count()
    • It returns the number of occurrences of value in given tuple.
    • T.count(value)
    • Example:
    • >>> x=(11,22,33,44,55,22,66,77,88,99,22)
      >>> x.count(22)
      3
      >>> x.count(44)
      1

List of built-in functions used with tuple

  • len()
    • It returns the integer value of number of items present in the tuple.
    • len(tuple)
  • min()
    • It returns minimum (integer or ordinal) value from tuple
    • min(tuple)
  • max()
    • It returns the maximum (integer or ordinal) value from the tuple
    • max(tuple)
    •  
  • sum()
    • This function returns the arithmetic sum of all the items in the tuple.
    • However, you can’t apply this function on a tuple with strings.
    • sum(tuple)
    • Example:
    • >>> k=(3,2,1)
      >>> sum(k)
      6
      >>> j=(5.5,2,4)
      >>> sum(j)
      11.5
      >>> i=('1','2','3')
      >>> sum(i)
      Traceback (most recent call last):
      File "<pyshell#11>", line 1, in
      sum(i)
      TypeError: unsupported operand type(s) for +: 'int' and 'str'
      >>>
  • any()
    • If even one item in the tuple has a Boolean value of True, then this function returns True. Otherwise, it returns False
    • >>> any(('','',8))
      True
    • The value 8 does have a Boolean value of True. If it was rather the integer 0, it would’ve returned False.
    • >>> any(('','',0))
      False
  • all()
    • Unlike any(), all() returns True only if all items have a Boolean value of True. Otherwise, it returns False.
    • >>> all(('1','2',8))
      True
      >>> all(('1','2',''))
      False
  • sorted()
    • This function returns a sorted version of the tuple. The sorting is in ascending order, and it doesn’t modify the original tuple in Python.
    • If we want to sort in descending order we can set reverse parameter as True.
    • sorted(tuple) #ascending order
      sorted(tuple, reverse=True) #descending order
    • Example:
    • >>> r=(7,6,8,4,3,1,9)
      >>> sorted(r)
      [1, 3, 4, 6, 7, 8, 9]
      >>> sorted(r,reverse=True)
      [9, 8, 7, 6, 4, 3, 1]
  • tuple()
    • This function converts another sequence like list, string etc into a Python tuple.
    • tuple(sequence)
    • Example:
    • >>> LL=['a',8.3,57,0.6]
      >>> tuple(LL)
      ('a', 8.3, 57, 0.6)
      >>> st='python'
      >>> tuple(st)
      ('p', 'y', 't', 'h', 'o', 'n')
      >>>

Example of tuple methods

tup=(9,8,7,6,5,4,3,2,1,0,1,2,3)
tupl=('itvoyagers','1',2 )
print(" length of tup: ",len(tup)) #length
print(" length of tupl: ",len(tupl)) #length
print(" maximum of tup: ",max(tup)) #max()
print(" min of tup: ",min(tup)) #min()
print("Total number of 2's in tuple",tup.count(2))
print("first occurence of 2 in tuple",tup.index(2))
a=[11,21,31,41,51]
print(" convert list to tuple: ",tuple(a)) #type conversion
c={1:5,2:6}
print(" convert dictionary to tuple: ",tuple(a)) #type conversion

 

Output of tuple methods in python

output of tuple methods

Variable - length argument tuples

Functions can take a variable number of arguments. A parameter name that begins with * collects arguments into a tuple.

Example:

def many_val(*args):
print(args)
many_val(8,7,5,3)
many_val(1)

Output

(8, 7, 5, 3)
(1,)

Tuples as return values

The built-in function divmod takes two arguments and returns a tuple of two values, the quotient and remainder. You can store the result as a tuple:

>>> z = divmod(4,3)
>>> z
(1, 1)
>>> e,f=divmod(13,6)
>>> e
2
>>> f
1

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
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