You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Basic list comprehensionsquares= [x**2forxinrange(10)]
# With conditioneven_squares= [x**2forxinrange(10) ifx%2==0]
# Dictionary comprehensionsquare_dict= {x: x**2forxinrange(5)}
# Set comprehensionunique_lengths= {len(word) forwordin ["hello", "world", "python"]}
Lambda Functions
# Basic lambdasquare=lambdax: x**2# With mapnumbers= [1, 2, 3, 4, 5]
squared=list(map(lambdax: x**2, numbers))
# With filterevens=list(filter(lambdax: x%2==0, numbers))
# With sortstudents= [("Alice", 85), ("Bob", 90), ("Charlie", 78)]
students.sort(key=lambdax: x[1]) # Sort by grade
Common Patterns
# Check if file existsimportosifos.path.exists("file.txt"):
print("File exists")
# Get current date/timefromdatetimeimportdatetimenow=datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
# Random operationsimportrandomrandom_number=random.randint(1, 100)
random_choice=random.choice(["apple", "banana", "cherry"])
# JSON operationsimportjsondata= {"name": "Alice", "age": 30}
json_string=json.dumps(data)
parsed_data=json.loads(json_string)
Debugging Tips
# Print debuggingprint(f"Debug: variable = {variable}")
# Type checkingprint(f"Type of variable: {type(variable)}")
# Check if variable existstry:
print(variable)
exceptNameError:
print("Variable not defined")
# Use assert for debuggingassertlen(my_list) >0, "List should not be empty"
Performance Tips
Use list comprehensions instead of loops when possible