I want to print all the elements in the range from 2 to 8 then use for loop:
E.g:
for i in range(2,8):
print(i)
What is the best method to iterate without using a for, or while loop, which reduces the time complexity?
How about using recursion?
def iterate(lst, start, end):
if start < 0 or end >= len(lst) or start > end:
return
print(lst[start])
iterate(lst, start + 1, end)
Call it like this:
iterate([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2, 8)
Let's take this sample list:
>>> mylist
['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
Now, let's print elements 2 through 8 without looping:
>>> ' '.join(mylist[2:9])
'two three four five six seven eight'
Here, 2:9 tells python to uses indices starting with 2 and continuing up to but not including 9.
x = range(20); sum(x[2:10])By slicing the list
>>> l = [1,2,3,4,5,6,7,8,9,10]
>>> print(l[1:8])
[2, 3, 4, 5, 6, 7, 8] # output in console
To get the summation of the values in l[1:8] use sum
>>> sum(l[1:8])
35 # output
EDIT because of @pzp:
If you want to print all the elements between index 2 and index 8 both inclusive,just replace print(l[1:8]) in the code above with print(l[2:9]).
l. I know that in Python indexes start at 0.n elements faster than going through each of the element.
str.joinalong with a slice of the list.