payment by upi: sinhamit@icici or payment by bank account name: amit kumar sinha, account number: 2646728782 IFSC code: KKBK0005660 SWIFT: KKBKINBB

Please support if you like my work by payment through upi: sinhamit@icici or payment by bank

account name: Amit Kumar Sinha,
account number: 2646728782
IFSC code: KKBK0005660
SWIFT: KKBKINBB


Tuple Methods   in Category: Python   by amit

🕙 Posted on 2023-08-11 at 18:45:50     Read in Hindi ...


Constructor Methods

    There are only two methods for tuple data-type: count() and index(). Many of you (readers) may argue that there are lots of methods shown for every built-in functions, when each of them, str, int, float, bool, list, tuple, etc. is placed within paren­theses of dir() and executed either in Python CLI >>> or in Command Prompt C:\xampp\htdocs\python2023> (or your project folder) after saving the code (in a file) with print() function.

print( dir( tuple ) )

print( help( tuple ) )

    These methods are also described in comparing different methods, which have two under­scores each on both ends. Those methods are known as constructor methods of a particular built-in function, each of which defines working of specific (common) operator, reserved keywords, etc.

    For example, __add__() defines how two or more operands will be added with + symbol (which is available for bool, int, float, complex, list, tuple, str, bytearray, bytes data-types). Similarly, __mul__() method defines how any of bool, int, float, complex, list, tuple, str, bytearray, bytes data-types, are multiplied with a integer value. A numeric data-type, such as boolean, integer or float can also be added and multiplied with boolean and float data-types.

    However, a string, list or tuple literal can only be concate­nated (either with + symbol or __add()__ method) with same data-type. That is, a string literal can only be concate­nated with a string data-type. A list literal can only be concate­nated with a list data-type. A tuple literal can only be concate­nated with a tuple data-type. Also, multiplying a string, list or tuple literal with non-int (other than integer data-type) will show ERROR.

print( help( tuple.__add__ ) )

Help on wrapper_descriptor:

__add__(self, value, /)
    Return self+value.

None

print( help( tuple.__mul__ ) )

Help on wrapper_descriptor:

__mul__(self, value, /)
    Return self*value.

None

Example 1

my_tuple = (1, 2, 3, 4)
new_tuple = (5, 6)
modified_tuple = tuple.__add__( my_tuple, new_tuple )
adding_tuples = my_tuple + new_tuple

print( my_tuple, new_tuple )
print( modified_tuple )
print( adding_tuples )

multi_tuple = tuple.__mul__( my_tuple, 3 )
many_tuple = my_tuple * 3

print( multi_tuple )
print( many_tuple )

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

    The first line in above output shows two separate tuples.

Example 2

print( (1, 2, 3, 4).__add__( (5, 6) ) )   # Outputs (1, 2, 3, 4, 5, 6) (same as above)

print( (1, 2, 3, 4).__mul__( 3 ) )   # Outputs (1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4) (same as above)

Example 3

print( "hello" + " world" )   # Outputs hello world

print( "hello" * 5 )   # Outputs hellohellohellohellohello

Example 4

print( [1, 2, 3] + [4, 5, 6] )   # Outputs [1, 2, 3, 4, 5, 6]

print( [1, 2, 3] * 4 )   # Outputs [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]

    These are ways as mentioned above, in which you can add or multiply strings, lists or tuples. However, these constr­uctor methods are rarely used for non-numeric data-types. (In old days, programmers do make their programs fancy with the help of these methods, for example:
******************************** (many asteriks) or
================================ many signs to show divider/separator in document­ation as described in ATLAS for different borders!)

    When you peruse (examine) carefully while comparing constru­ctor methods of same name for different data-types, you will be surprised that, many methods may not be available for other data-types. For example __add__() and __mul__() methods are not available for dictionary, set, frozenset, memoryview data-types.

    __len__ method available for a data-type means that len() built-in function can be applied on that particular data-type. You have already seen in previous page that len() cannot be applied on numbers and booleans. Some constructor methods and their respective equivalent operators are shown below.

__add____mul____ge____gt____le____lt__
+*>=><=<
__iadd____imul____eq____ne____len__x.__getitem__(y)
+=*===!=len()x[y]

    x.__getitem__(y) method is equi­valent to x[y] where x is string, list, tuple or dictionary data-type literal and y is the index number or key name. Thus, you can use either __getitem__() or a pair of square brackets to extract the item/element or character(s) as the case may be.

    Similarly, x.__setitem__(y, value) method (only available for list, dictionary, bytearray, and memoryview data-types) is equivalent to x[y] = value that is, the value of an item/element can be changed either using x.__setitem__(y, value) or x[y] = value.

print( help( tuple.__sizeof__ ) )

Help on method_descriptor:

__sizeof__(self, /)
    Size of object in memory, in bytes.

None

Example 1 (continued)

print( tuple.__sizeof__( my_tuple ) )
print( tuple.__sizeof__( new_tuple ) )
print( tuple.__sizeof__( modified_tuple ) )
print( tuple.__sizeof__( adding_tuples ) )

56
40
72
72

    The __sizeof__() methods does not take any arguments within the paren­theses, and outputs the memory size (of the object in RAM) in bytes.

print( (1, 2, 3, 4).__mul__( 3 ).__sizeof__() )   # Outputs 120 (it may be different because different operating systems may store the value of output differ­ently!)

    You can see that __dir__ and __doc__ methods are available for every data-types. __dir__ is equivalent to dir() built-in function. __doc__ method when follows some data-type literal, or built-in functions for those data-types, for example, print( tuple.__doc__ ) outputs the introduction docstring (first few lines) of print( help( tuple ) ). You will learn more about __doc__ method, when creating custom functions and their docstrings.

print( help( tuple.__dir__ ) )

Help on method_descriptor:

__dir__(self, /)
    Default dir() implementation.

None

Other Constructor Methods for Integers, Floats, Booleans, etc.

__abs____and____bool____float____floordiv____int__
abs()&True except 0 which is Falsefloat()//int()

print( help( int.__pos__ ) )

Help on wrapper_descriptor:

__pos__(self, /)
    +self

None

print( help( int.__neg__ ) )

Help on wrapper_descriptor:

__neg__(self, /)
    -self

None

    The __pos__ and __neg__ methods define the positive and negative character of a number. Identity and negation can be done by prefixing + and - sign before any number or numeric string. For example, +1 (identity of 1 in other programming languages) and -1 (negation of 1) are generally used in mathe­matical operations. These two are different from __add__ (addition operator) and __sub__ (subtra­ction operator), which takes two arguments/operands (self and value − see above).

    It is useful to peruse and examine with help() and dir() built-in functions regularly to know that any built-in function or method can be applied on a particular data-type or not. However, it is not recomm­ended to use these constru­ctor methods strictly! For example, concate­nation, slicing, extraction, addition, multi­plica­tion, positivity (identity), negativity (negation), etc. can easily be done with respective operators and syntaxes.


Leave a Comment: