Core Python Features for Elegant and Efficient Programming
Python's design emphasizes readability and developer productivity through a variety of syntactic constructs and language features.
Concise List Creation with Comprehensions
List comprehensions offer a compact syntax for generating lists, replacing verbose loops.
# Using a standard for-loop
result_list = []
for num in range(5):
result_list.append(num * 3)
# Equivalent list comprehension
result_list = [num * 3 for num in range(5)]
Simultaneous Variable Assignment and Swapipng
Multiple assignment and tuple unpacking allow for clean variable manipulasion.
x, y = 10, 20
x, y = y, x # Swaps the values of x and y
Flexible Function Arguments
Default and keyword arguments enhance function usability and clarity.
def send_message(recipient, text='Hi there'):
print(f"{text}, {recipient}")
send_message('Charlie') # Output: Hi there, Charlie
send_message('Dana', 'Welcome') # Output: Welcome, Dana
Lazy Evaluation with Generators
Generators produce items one at a timee, conserving memory for large or infinite sequences.
def count_up_to(limit):
current = 0
while current < limit:
yield current
current += 1
for number in count_up_to(7):
print(number)
Modifying Behavior with Decorators
Decorators wrap functions to add functionality without altering they core code.
def log_call(func):
def inner(*args, **kwargs):
output = func(*args, **kwargs)
print(f"Function '{func.__name__}' produced: {output}")
return output
return inner
@log_call
def multiply(p, q):
return p * q
multiply(5, 6)
Resource Management using Context Managers
The with statement ensures proper setup and teardown of resources like files.
with open('data.log', 'a') as log_file:
log_file.write('New entry\n')
Duck Typing and Polymorphism
Python focuses on an object's capabilities (methods) rather than its explicit type.
class Bird:
def sound(self):
print("Chirp chirp!")
class Human:
def sound(self):
print("I can make a sound!")
def make_noise(creature):
creature.sound()
sparrow = Bird()
artist = Human()
make_noise(sparrow) # Output: Chirp chirp!
make_noise(artist) # Output: I can make a sound!
Structured Error Handling with Try-Except
Exception handling gracefully manages runtime errors.
try:
value = 100 / 0
except ZeroDivisionError:
print("Division by zero is not permitted.")
Efficient Sequence Operations with Slicing
Slicing provides a powerful way to extract subsequences from lists, strings, and other iterables.
data = ['a', 'b', 'c', 'd', 'e', 'f']
print(data[1:4]) # Output: ['b', 'c', 'd']
Introspection and Runtime Modification
Python's reflection capabilities allow enspection and dynamic alteration of objects.
class Example:
def demo(self):
return 42
instance = Example()
print(hasattr(instance, 'demo')) # Checks for the 'demo' attribute