🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this guide, you'll explore Python's operator module, which provides efficient functions for standard operators. Learn its features and examples for cleaner code.
The operator module in Python provides a set of efficient functions corresponding to the intrinsic operators of Python. These functions allow you to perform operations using a functional programming style, making your code cleaner and more readable.
Table of Contents
- Introduction
- Arithmetic Operators
addsubmultruedivfloordivmodpow
- Bitwise Operators
and_or_xorinvertlshiftrshift
- Comparison Operators
eqneltlegtge
- Logical Operators
not_truthis_is_not
- Sequence Operators
concatcontainscountOfindexOfgetitemsetitemdelitem
- Attribute and Item Getters
attrgetteritemgettermethodcaller
- Examples
- Basic Arithmetic Operations
- Using
itemgetterandattrgetter - Sorting with Custom Keys
- Real-World Use Case
- Conclusion
- References
Introduction
The operator module exports a set of functions that correspond to standard Python operations. These functions can be used to replace lambda functions, making your code cleaner and more efficient.
Arithmetic Operators
add
Returns the sum of a and b.
import operator
print(operator.add(10, 5)) # 15
sub
Returns the difference of a and b.
print(operator.sub(10, 5)) # 5
mul
Returns the product of a and b.
print(operator.mul(10, 5)) # 50
truediv
Returns the division of a by b.
print(operator.truediv(10, 5)) # 2.0
floordiv
Returns the floor division of a by b.
print(operator.floordiv(10, 3)) # 3
mod
Returns the remainder of a divided by b.
print(operator.mod(10, 3)) # 1
pow
Returns a raised to the power of b.
print(operator.pow(2, 3)) # 8
Bitwise Operators
and_
Returns the bitwise AND of a and b.
print(operator.and_(6, 3)) # 2
or_
Returns the bitwise OR of a and b.
print(operator.or_(6, 3)) # 7
xor
Returns the bitwise XOR of a and b.
print(operator.xor(6, 3)) # 5
invert
Returns the bitwise inversion of a.
print(operator.invert(2)) # -3
lshift
Returns a shifted left by b bits.
print(operator.lshift(2, 2)) # 8
rshift
Returns a shifted right by b bits.
print(operator.rshift(8, 2)) # 2
Comparison Operators
eq
Returns True if a is equal to b.
print(operator.eq(10, 10)) # True
ne
Returns True if a is not equal to b.
print(operator.ne(10, 5)) # True
lt
Returns True if a is less than b.
print(operator.lt(10, 5)) # False
le
Returns True if a is less than or equal to b.
print(operator.le(10, 10)) # True
gt
Returns True if a is greater than b.
print(operator.gt(10, 5)) # True
ge
Returns True if a is greater than or equal to b.
print(operator.ge(10, 10)) # True
Logical Operators
not_
Returns the negation of a.
print(operator.not_(True)) # False
truth
Returns True if a is true.
print(operator.truth([])) # False
is_
Returns True if a is b.
print(operator.is_(None, None)) # True
is_not
Returns True if a is not b.
print(operator.is_not(None, 5)) # True
Sequence Operators
concat
Concatenates two sequences.
print(operator.concat([1, 2], [3, 4])) # [1, 2, 3, 4]
contains
Returns True if a contains b.
print(operator.contains([1, 2, 3], 2)) # True
countOf
Returns the count of b in a.
print(operator.countOf([1, 2, 2, 3], 2)) # 2
indexOf
Returns the first index of b in a.
print(operator.indexOf([1, 2, 3], 2)) # 1
getitem
Returns the item of a at index b.
print(operator.getitem([1, 2, 3], 1)) # 2
setitem
Sets the item of a at index b to c.
lst = [1, 2, 3]
operator.setitem(lst, 1, 4)
print(lst) # [1, 4, 3]
delitem
Deletes the item of a at index b.
lst = [1, 2, 3]
operator.delitem(lst, 1)
print(lst) # [1, 3]
Attribute and Item Getters
attrgetter
Returns a callable object that fetches the given attribute(s) from its operand.
from operator import attrgetter
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
people = [Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35)]
people.sort(key=attrgetter('age'))
print([person.name for person in people]) # ['Bob', 'Alice', 'Charlie']
itemgetter
Returns a callable object that fetches the given item(s) from its operand.
from operator import itemgetter
data = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 35}]
data.sort(key=itemgetter('age'))
print([person['name'] for person in data]) # ['Bob', 'Alice', 'Charlie']
methodcaller
Returns a callable object that calls the given method on its operand.
from operator import methodcaller
s = "hello"
print(methodcaller('upper')(s)) # HELLO
Examples
Basic Arithmetic Operations
import operator
a, b = 10, 5
print(operator.add(a, b)) # 15
print(operator.sub(a, b)) # 5
print(operator.mul(a, b)) # 50
print(operator.truediv(a, b)) # 2.0
Using itemgetter and attrgetter
from operator import itemgetter, attrgetter
data = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 35}]
sorted_data = sorted(data, key=itemgetter('age'))
print(sorted_data) # [{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Charlie', 'age': 35}]
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
people = [Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35)]
sorted_people = sorted(people, key=attrgetter('
age'))
print([(person.name, person.age) for person in sorted_people]) # [('Bob', 25), ('Alice', 30), ('Charlie', 35)]
Sorting with Custom Keys
from operator import itemgetter
data = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 35}]
data.sort(key=itemgetter('name'))
print(data) # [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 35}]
Real-World Use Case
Sorting Complex Data Structures
The operator module is particularly useful when sorting complex data structures like lists of dictionaries or objects. It allows for concise and readable code.
from operator import itemgetter
students = [
{'name': 'John', 'age': 21, 'grade': 'B'},
{'name': 'Jane', 'age': 22, 'grade': 'A'},
{'name': 'Dave', 'age': 20, 'grade': 'C'}
]
# Sort by age
sorted_by_age = sorted(students, key=itemgetter('age'))
print(sorted_by_age)
# Sort by grade, then by name
sorted_by_grade_name = sorted(students, key=itemgetter('grade', 'name'))
print(sorted_by_grade_name)
Output:
[{'name': 'Dave', 'age': 20, 'grade': 'C'}, {'name': 'John', 'age': 21, 'grade': 'B'}, {'name': 'Jane', 'age': 22, 'grade': 'A'}]
[{'name': 'Jane', 'age': 22, 'grade': 'A'}, {'name': 'John', 'age': 21, 'grade': 'B'}, {'name': 'Dave', 'age': 20, 'grade': 'C'}]
Conclusion
The operator module in Python provides a suite of functions corresponding to intrinsic operators, making it easier to perform operations in a functional programming style. These functions help improve the readability and efficiency of the code, especially when dealing with complex data structures.
Comments
Post a Comment
Leave Comment