range() function in python code example
Example 1: for i in range python
#coding: utf-8
for item in range(10):
print(item)
Example 2: python range
# range(start, stop, step)
# start = (can be ommitted) index to begin at (INCLUSIVE)
# stop = generate numbers up to, but not including this number (EXCLUSIVE)
# step = (can be omitted) difference between each number in the sequence
# idx: 0 1 2 3 4
# arr: 19 5 3 22 13
arr = [19,5,3,22,13]
# range(stop)
for i in range(len(arr)):
print(arr[i]) # prints: 19, 5, 3, 22, 13
# range(start, stop)
for i in range(2, len(arr)):
print(arr[i]) # prints: 3, 22, 13
# range(start, stop, step)
for i in range(0, len(arr), 2):
print(arr[i]) # prints: 19, 3, 13
# reverse:
for i in range(len(arr)-1, -1, -1):
print(arr[i])
Example 3: python 3 numbers of a range is even
def check(element):
return all(ord(i)%2 == 0 for i in element) # all returns True if all digits i is even in element
lst = [str(i) for i in range(1000,3001)] # creates list of all given numbers with string data type
lst = list(filter(check,lst)) # filter removes element from list if check condition fails
print(",".join(lst))
Example 4: in range python
for i in range(x) :
#code
Example 5: range(n,n) python
# if numbers are same in the range function then,
# the range function outputs empty range
# this is because, there are no integers b/w n and n
for i in range(1,1):
print("runs")
# prints nothing
Example 6: range() python
#can be used a sequence of numbers
x = range(6)
print(x)
#Outputs 0 1 2 3 4 5
for i in range(start,finish ,step)
#gives range of numbers
#start is optional default is 0
#finish needed specifying when to stop
#step is incremetntaition of jump also optional