F-strings (formatted string literals) were introduced in Python 3.6 to improve string formatting by making it more readable and efficient. Instead of using .format() or % formatting, f-strings allow direct variable insertion using {}.
Benefits:
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
The walrus operator (:=) introduced in Python 3.8 allows assignment inside an expression. It is useful in loops and conditions where a value needs to be assigned and checked simultaneously.
Use cases:
while (n := len(input("Enter string: "))) > 5:
print(f"Length is {n}, try a shorter string.")
== compares values (whether two objects have the same content) while is compares identities (whether two variables point to the same memory location).
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True (values are the same)
print(a is b) # False (different memory locations)
enumerate() provides an index while iterating, making code cleaner and more readable compared to range(len()).
Advantages:
names = ["Alice", "Bob", "Charlie"]
for index, name in enumerate(names, start=1):
print(f"{index}: {name}")
Mutable objects can be changed after creation (e.g., lists, dictionaries, sets).
Immutable objects cannot be changed after creation (e.g., tuples, strings, integers).
# Mutable (List)
my_list = [1, 2, 3]
my_list[0] = 10 # Allowed
print(my_list) # Output: [10, 2, 3]
# Immutable (Tuple)
my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # TypeError: 'tuple' object does not support item assignment
[]
) – Ordered, mutable, allows duplicates. Use when the order is important.()
) – Ordered, immutable, allows duplicates. Use when data shouldn’t change.{}
) – Unordered, mutable, no duplicates. Use for unique items.{key: value}
) – Key-value pairs, fast lookups. Use for mapping data.*args
and **kwargs
in Python functions?*args
allows passing a variable number of positional arguments.**kwargs
allows passing a variable number of keyword arguments.
def demo_function(*args, **kwargs):
print("Positional:", args)
print("Keyword:", kwargs)
demo_function(1, 2, 3, name="edSlash", age=25)
# Output:
# Positional: (1, 2, 3)
# Keyword: {'name': 'edSlash', 'age': 25}
zip()
in Python?The zip()
function combines multiple iterables element-wise into tuples.
names = ["edSlash", "Coding", "Hub", "Gwalior"]
ages = [25, 20, 22, 27]
combined = list(zip(names, ages))
print(combined) # [('edSlash', 25), ('Coding', 20), ('Hub', 22), ('Gwalior', 27)]
Lambda functions are anonymous, single-expression functions used for short tasks.
square = lambda x: x ** 2
print(square(5)) # Output: 25
students = [("Alice", 25), ("Bob", 20), ("Charlie", 22)]
students.sort(key=lambda x: x[1]) # Sort by age
print(students) # [('Bob', 20), ('Charlie', 22), ('Alice', 25)]
nums = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, nums))
print(squared) # [1, 4, 9, 16]
List comprehensions provide a concise way to create lists.
# squares = []
# for x in range(5):
# squares.append(x**2)
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
# Both codes will give the same output but the 2nd one is smaller.
Exception handling prevents programs from crashing due to unexpected errors.
try:
x = 1 / 0 # ZeroDivisionError
except ZeroDivisionError:
print("You cannot divide by zero!")
finally:
print("This will always execute.")
# Output ---
# You cannot divide by zero!
# This will always execute.
in
keyword work in Python?The in
keyword is used to check if a data value is member of a sequence (lists, tuples, sets, dict or strings) or not.
print("edSlash" in ["Coding", "edSlash", "Hub"])
# --- Output ---
# True
__name__ == "__main__"
in Python?It ensures that a script(Python code) runs only when executed directly, not when imported as a module.
def greet():
print("Hello, world!")
if __name__ == "__main__":
greet() # Runs only if the script is executed directly
map()
, filter()
, and reduce()
functions?map(func, iterable)
: Applies a function to all elements.filter(func, iterable)
: Filters elements based on a condition.reduce(func, iterable)
: Reduces an iterable to a single value (needs functools
).
from functools import reduce
nums = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, nums))
filtered = list(filter(lambda x: x % 2 == 0, nums))
summed = reduce(lambda x, y: x + y, nums)
print(squared) # [1, 4, 9, 16, 25]
print(filtered) # [2, 4]
print(summed) # 15
deepcopy()
and copy()
in Python?copy()
creates a shallow copy, meaning it copies only the reference to nested objects.deepcopy()
creates an independent deep copy of all nested objects.
import copy
original = [[1, 2, 3], [4, 5, 6]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original[0][0] = 99
print(shallow[0][0]) # 99 (Shallow copy affected)
print(deep[0][0]) # 1 (Deep copy remains unchanged)
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
merged = {**dict1, **dict2} # Using dictionary unpacking
print(merged) # {'a': 1, 'b': 3, 'c': 4}
dict1.update(dict2) # Using update()
print(dict1) # {'a': 1, 'b': 3, 'c': 4}
isinstance()
and type()
in Python?isinstance(obj, Class)
: Checks if an object is an instance of a class (including subclasses).type(obj)
: Checks the exact type (ignores inheritance).
print(isinstance(5, int)) # True
print(isinstance(True, int)) # True (since bool is a subclass of int)
print(type(5) == int) # True
print(type(True) == int) # False
f-strings (formatted string literals) allow embedding expressions inside string literals using {}
. They are more readable and efficient than older formatting methods like format()
and %
.
name = "edSlash"
age = 28
print(f"My name is {name} and I am {age} years old.")
# Output: My name is edSlash and I am 28 years old.
# Using set() (order is lost):
nums = [1, 2, 2, 3, 4, 4, 5]
unique_nums = list(set(nums))
print(unique_nums) # Output: [1, 2, 3, 4, 5]
# Using dict.fromkeys() (preserves order):
unique_nums = list(dict.fromkeys(nums))
print(unique_nums) # Output: [1, 2, 3, 4, 5]
# Using list comprehension:
unique_nums = []
[unique_nums.append(num) for num in nums if num not in unique_nums]
print(unique_nums) # Output: [1, 2, 3, 4, 5]
Office:- 660, Sector 14A, Vasundhara, Ghaziabad, Uttar Pradesh - 201012, India