Loading notes...
Loading notes...
B.Tech • Chapter 2
B.Tech level module on Advanced Control Flow & Loops.
Control flow statements guide the execution path of a program. While basic if/else and loops are standard, B.Tech curriculum demands optimization. For instance, list comprehensions provide a more concise and often faster way to create lists than standard for-loops.
Advanced Engineering Concepts
Loop optimization is critical. Using built-in functions like enumerate(), zip(), and map() can significantly reduce execution time (Time Complexity) compared to manual indexing in a while loop. Additionally, the 'else' clause in a for-loop is a unique Python feature that executes only if the loop is NOT terminated by a break statement.
Code Implementation
# Standard loop vs Comprehension
import timeit
# Standard
def loop_func():
res = []
for i in range(1000):
res.append(i * 2)
return res
# Comprehension
def comp_func():
return [i * 2 for i in range(1000)]
print("Loop:", timeit.timeit(loop_func, number=10000))
print("Comp:", timeit.timeit(comp_func, number=10000))