Python for Loop

February 24, 2019
nums = [1, 2, 3, 4, 5]

Element iteration

Loop all element

for value in nums:
  print(value)

Loop from n-th element

for value in nums[n:]:
  print(value)

Loop to n-th element

for value in nums[:n]:
  print(value)

Access index0 as well.

for index, value in enumerate(nums):
  print(index) # 0, 1, 2, 3, 4

Access index1 as well.

for index, value in enumerate(nums, start=1):
  print(index) # 1, 2, 3, 4, 5

With Index

Python for loop, start from index 0.

for i in range(len(nums)): # 0,1,2,3,4
  print(nums[i]) 

In Python 2

  • range return list of numbers (all numbers pre-created).
  • xrange return xrange object (number is created on demand).
type(range(5))  # <type 'list'>
type(xrange(5)) # <type 'xrange'>

Python 3 range is similar to Python 2 xrange, but not exactly the same. There is no xrange for python 3.

To convert Python 3 range to list.

list(range(5))

Python for loop, start from index 1.

for i in range(1, len(nums)+1): # 1,2,3,4,5
  print(nums[i-1])

Python for loop, reverse fron n-1 to 0.

for i in range(len(nums)-1, -1, -1): # 4, 3, 2, 1, 0
  print(nums[i])
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.