for i in range array python code example

Example 1: python how to get index in for loop

# There are two ways to do this
# The "beginner" one:
index = 0
foods = ["burger", "pizza", "apple", "donut", "coconut"]
for food in foods:
  print("Food", index, "is", food)
  index += 1

# Or using enumerate:
foods = ["burger", "pizza", "apple", "donut", "coconut"]
for index, value in enumerate(foods):
    print("Food", index, "is", value)

# By convention, you should understand and use the enumerate function as it makes the code look much cleaner.

Example 2: how to iterate through range in python

for i in range(start, end):
    dosomething()
#The i is an iteration variable that you can replace by anytthing. You do not need to define it.

Example 3: for i in range python

#coding: utf-8

for item in range(10):
    print(item)

Example 4: python for loop index

# Creates two variables; An index (num), and the value at that index (line)
for num, line in enumerate(lines):
    print("{0:03d}: {}".format(num, line))

Example 5: python range of array

>>> new_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(new_list[5:9])
[6, 7, 8, 9]

Example 6: for i in range python

for i in range(start, end):
  expression