DEV Community

Super Kai (Kazuya Ito)
Super Kai (Kazuya Ito)

Posted on

range in Python

Buy Me a Coffee

*Memos:

range() can create a sequence of numbers as shown below:
*Memos:

  • The 1st argument is start(Optional-Default:0-Type:int).
  • The 2nd argument is stop(Required-Type:int).
  • The 3rd argument is step(Optional-Default:1-Type:int).
  • start=, stop= and step= cannot be used.
print(range(4))
print(range(0, 4))
print(range(0, 4, 1))
# range(0, 4)

print(range(4).start, range(4).stop, range(4).step)
# 0 4 1

print(list(range(4)))
# [0, 1, 2, 3]

print(range(4)[0], range(4)[1], range(4)[2], range(4)[3])
# 0 1 2 3

print(list(range(-5, 12, 3)))
# [-5, -2, 1, 4, 7, 10]

print(list(range(12, -5, -3)))
# [12, 9, 6, 3, 0, -3]

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

for i in range(-5, 12, 3):
    print(i)
# -5
# -2
# 1
# 4
# 7
# 10

for i in range(12, -5, -3):
    print(i)
# 12
# 9
# 6
# 3
# 0
# -3
Enter fullscreen mode Exit fullscreen mode
fruits = ["Apple", "Orange", "Banana", "Kiwi", "Lemon", "Mango"]

for i in range(4):
for i in range(0, 4):
for i in range(0, 4, 1):
    print(fruits[i])
# Apple
# Orange
# Banana
# kiwi

for i in range(1, 6, 2):
    print(fruits[i])
# Orange
# Kiwi
# Mango

for i in range(5, 0, -2):
    print(fruits[i])
# Mango
# Kiwi
# Orange
Enter fullscreen mode Exit fullscreen mode
print(list(zip(range(4), range(-5, 12, 3), range(12, -5, -3))))
# [(0, -5, 12), (1, -2, 9), (2, 1, 6), (3, 4, 3)]

for i, j, k in zip(range(4), range(-5, 12, 3), range(12, -5, -3)):
    print(i, j, k)
# 0 -5 12
# 1 -2 9
# 2 1 6
# 3 4 3

list(enum(zip(range(4), range(-5, 12, 3), range(12, -5, -3)), 7))
# [(7, (0, -5, 12)), (8, (1, -2, 9)), (9, (2, 1, 6)), (10, (3, 4, 3))]

for i, jkl in enum(zip(range(4), range(-5, 12, 3), range(12, -5, -3)), 7):
    print(i, jkl)
# 7 (0, -5, 12)
# 8 (1, -2, 9)
# 9 (2, 1, 6)
# 10 (3, 4, 3)

print(list(enum(zip(range(4), range(-5, 12, 3), range(12, -5, -3)), 7)))
# [(7, (0, -5, 12)), (8, (1, -2, 9)), (9, (2, 1, 6)), (10, (3, 4, 3))]

for i, (j, k, l) \
  in enum(zip(range(4), range(-5, 12, 3), range(12, -5, -3)), 7):
for i, [j, k, l] \
  in enum(zip(range(4), range(-5, 12, 3), range(12, -5, -3)), 7):
    print(i, j, k, l)
# 0 0 -5 12
# 1 1 -2 9
# 2 2 1 6
# 3 3 4 3
Enter fullscreen mode Exit fullscreen mode

Top comments (0)