3

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?

1
  • 1
    Use str.join along with a slice of the list. Commented Aug 11, 2016 at 3:00

4 Answers 4

6

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Very nice solution. Perhaps you should generalize your function for any start and end index.
@pzp thanks! I updated my answer :)
3

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.

6 Comments

Thanks! Suppose I have a list of 20 numbers, how do I get the sum of numbers between 2 and 9 without using a loop?
@Falcon2908 , that's a completely different question. Please submit a new one.
x = range(20); sum(x[2:10])
@Falcon2908 That's a separate question so you should either figure it out yourself (it's not too big of a logical jump from the code that John1024 gave you) or ask a new question.
@Falcon2908 Please see my answer to find the sum.
|
2

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]).

6 Comments

Looks like you have an off-by-one error in your slice indices.
@pzp Nope, I did chose [1:8] on purpose because I want to list 2 to 8 in the list l. I know that in Python indexes start at 0.
The OP asked for "the elements between index 2 and 8" (not value 2 and 8) and your answer gives the elements between index 1 and 8.
@Ralf17, if you use sum() function, doesn't it behave as a for loop with complexity O (n) ?
@Falcon2908: You can't sum a list of n elements faster than going through each of the element.
|
2

simple solution using list comprehension

list1 = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
sum1 = sum([i for i in list1 if i > 2 and i < 9])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.