1When you call range() with three arguments, you can choose not only
2where the series of numbers will start and stop but also how big the
3difference will be between one number and the next.
4
5range(start, stop, step)
6
7If your 'step' is negative and 'start' is bigger than 'stop', then
8you move through a series of decreasing numbers.
9
10for i in range(10,0,-1):
11 print(i, end=' ')
12# Output: 10 9 8 7 6 5 4 3 2 1
1# 1.
2for i in reversed(range(3)): # output: 0
3 print(i) # 1
4 # 2
5# works with arrays as well , reversed(arr)
6
7# 2.
8# another alternative is
9arr = [1,2,3]
10# note: arr[start : end : step]
11for i in arr[::-1]: # output: 0
12 print(i) # 1
13 # 2
14
15# 3.
16# last alternative i don't recommened!
17# note: range(start, end, step)
18for i in range(len(arr) - 1, -1 , -1): # output: 0
19 print(i) # 1
20 # 2
21# read more on range() to understand even better how it works has the same rules as the arrays
1# Python string/number reverser
2example_number = 12143
3example_string = "Hello there"
4
5def reverse(thing):
6 thing = str(thing) # convert it to a string, just in case it was a number
7 list_of_chars = [char for char in thing]
8 reversed_list_of_chars = []
9 x = -1
10
11 for char in list_of_chars:
12 reversed_list_of_chars.append(list_of_chars[x])
13 x += -1
14
15 reversed_thing = ''.join(reversed_list_of_chars)
16
17 return reversed_thing
18 # Or alternatively do:
19 print(reversed_thing)
20
21# Run it by doing this
22reverse(example_number)
23reverse(example_string)
1my_list = [1, 2, 3]
2my_list.reverse() # my_list is modified
3print(my_list) # '[3, 2, 1]'
4my_revert = my_list[::-1] # my_list stays [3, 2, 1]
5print(my_revert) # '[1, 2, 3]'
6# Item by item reverse with range(<start>, <end>, <step>)
7for i in range(len(my_list), 0, -1): # my_list is [3, 2, 1]
8 print(my_list[i-1]) # '1' '2' '3'
9for i in reversed(range(len(my_list))):
10 print(my_list[i]) # '1' '2' '3'
1range(4)
2#considers numbers 0,1,2,3
3range(1, 4)
4#considers numbers 1,2,3
5range(1, 4, 2)
6#considers numbers 1,3
7range(4, 1, -1)
8#considers numbers 4,3,2