Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: iterate a specific range in a list

Lets say I have a list:

listOfStuff =([a,b], [c,d], [e,f], [f,g])

What I want to do is to iterate through the middle 2 components in a way similar to the following code:

for item in listOfStuff(range(2,3))
   print item

The end result should be as below:

[c,d]
[e,f]

This code currently does not work, but I hope you can understand what I am trying to do.

like image 928
ccwhite1 Avatar asked Mar 31 '11 14:03

ccwhite1


People also ask

How do you increment a range in Python?

Incrementing the values in range using a positive step. The parameter step in range() can be used to increment /decrement the values. By default, it is a positive value 1. So it will always give incremented values. The step value has to be positive incase you want to want incremented values as ouput.


4 Answers

listOfStuff =([a,b], [c,d], [e,f], [f,g])

for item in listOfStuff[1:3]:
    print item

You have to iterate over a slice of your tuple. The 1 is the first element you need and 3 (actually 2+1) is the first element you don't need.

Elements in a list are numerated from 0:

listOfStuff =([a,b], [c,d], [e,f], [f,g])
               0      1      2      3

[1:3] takes elements 1 and 2.

like image 102
eumiro Avatar answered Oct 03 '22 00:10

eumiro


A more memory efficient way to iterate over a slice of a list would be to use islice() from the itertools module:

from itertools import islice

listOfStuff = (['a','b'], ['c','d'], ['e','f'], ['g','h'])

for item in islice(listOfStuff, 1, 3):
    print(item)

# ['c', 'd']
# ['e', 'f']

However, this can be relatively inefficient in terms of performance if the start value of the range is a large value since islice would have to iterate over the first start value-1 items before returning items.

like image 24
martineau Avatar answered Oct 03 '22 00:10

martineau


You want to use slicing.

for item in listOfStuff[1:3]:
    print item
like image 26
Håvard Avatar answered Oct 02 '22 23:10

Håvard


By using iter builtin:

l = [1, 2, 3]
# i is the first item.
i = iter(l)
next(i)
for d in i:
    print(d)
like image 42
Elior Malul Avatar answered Oct 03 '22 00:10

Elior Malul