FirstHack Learn
Log in Sign up free
Lessons in this course 0/6 All courses Python for Engineering Students

First year

Progress0 / 6 lessons
  1. 1. Why Python reads the way it does
  2. 2. Variables, types and f-strings
  3. 3. Lists, tuples, dicts and sets
  4. 4. Loops, comprehensions and enumerate
  5. 5. Functions, default arguments and *args
  6. 6. Files, exceptions and context managers

Courses › Python for Engineering Students

Loops, comprehensions and enumerate

for, while, range, zip and list comprehensions - plus when a comprehension is the wrong choice.

11 min read · Lesson 4 of 6 · Pro

Python's for loop is not C's for loop

C's loop is a counter: start, condition, step. Python's for walks over the items of a collection directly.

Python 3
marks = [72, 65, 88]

for m in marks:
    print(m)

There is no index. You asked for the items, so you get the items. When you genuinely need a counter, range makes one.

Python 3
for i in range(5):        # 0 1 2 3 4
    print(i)

for i in range(1, 6):     # 1 2 3 4 5
    print(i)

for i in range(10, 0, -2):  # 10 8 6 4 2
    print(i)

range(a, b) stops before b. That is deliberate: range(0, n) gives exactly n values, and range(0, 5) plus range(5, 10) covers 0 to 9 with no gap and no overlap.

The rest of this lesson is Pro

The free lessons of Python for Engineering Students finish what they start — read those first if you have not. This one goes further, and it is part of the paid half.

A pass opens the paid lessons of every course, the mock test papers and the company-wise series. It ends on its own date; nothing renews by itself.

Get a pass — from ₹29 for 7 days

Already bought one? Log in.