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 parentheses of dir()
and executed either in Python CLI >>> or in Command Prompt C:\xampp\
print( dir( tuple ) )
print( help( tuple ) )
These methods are also described in comparing different methods, which have two underscores 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 concatenated (either with + symbol or __add()__ method) with same data-type. That is, a string literal can only be concatenated with a string data-type. A list literal can only be concatenated with a list data-type. A tuple literal can only be concatenated 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__ ) )
__add__(self, value, /)
Return self+value.
None
print( help( tuple.__mul__ ) )
__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, 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 hellohello
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 constructor 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:
********
========
When you peruse (examine) carefully while comparing constructor 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 equivalent 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/
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/__setitem__
(y, value) or x[y] = value.
print( help( tuple.__sizeof__ ) )
__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 ) )
40
72
72
The __sizeof__()
methods does not take any arguments within the parentheses, 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 differently!)
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__ ) )
__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 False | float() | // | int() |
print( help( int.__pos__ ) )
__pos__(self, /)
+self
None
print( help( int.__neg__ ) )
__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 mathematical operations. These two are different from __add__ (addition operator) and __sub__ (subtraction operator), which takes two arguments/
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 recommended to use these constructor methods strictly! For example, concatenation, slicing, extraction, addition, multiplication, positivity (identity), negativity (negation), etc. can easily be done with respective operators and syntaxes.
Leave a Comment:
Amit Sinha March 2nd, 2023 at 9:30 PM
😃 😄 😁 😆 😅 😂 😉 😊 😇 😍 😘 😚 😋 😜 😝 😶 😏 😒 😌 😔 😪 😷 😵 😎 😲 😳 😨 😰 😥 😢 😭 😱 😖 😣 😞 😓 😩 😫 😤
Ribhu March 3rd, 2023 at 9:30 PM
🐵 🐒 🐶 🐩 🐺 🐱 🐯 🐅 🐆 🐴 🐎 🐮 🐂 🐃 🐄 🐷 🐖 🐗 🐽 🐏 🐑 🐐 🐪 🐫 🐘 🐭 🐁 🐀 🐹 🐰 🐇