Pythonic loops - how to get multiple items when repeating a list

I want to iterate over my list and do something with several elements, not just one element. I want to take the first element and some elements after it (they can be consecutive or, possibly, the third element from the returned one).

l = ['a', 'b', 'c', 'd', 'e']
  for items in l:
    print items[:3]

The output should be:

['a', 'b', 'c'], ['b', 'c', 'd'], ['c', 'd', 'e']

There are many good answers, what if you want to skip elements? Say, get the item, skip the next item and get the third item?

Conclusion:

('a', 'c'), ('b','d'), ('c', 'e')

I guess enumeration is the best way to handle this?

List iteration is so simple and elegant. I was hoping that such a syntax would allow you to use it inside the for loop for the element itself and not use a range or enumeration.

l = ['a', 'b', 'c', 'd', 'e']
  for items in l:
    print (items[0], items[2])

(, , , , . [[1, 2, 3], [4, 5, 6], [7, 8, 9]] return [1, 3], [4, 6], [7, 9])

+3
7
l = ['a', 'b', 'c', 'd', 'e']
subarraysize = 3
for i in range(len(l)-subarraysize+1):
    print l[i:i+subarraysize]

:

['a', 'b', 'c']
['b', 'c', 'd']
['c', 'd', 'e']

Pythonic, , .

+3

zip slicing:

l = range(5)
for grp in zip(*[l[i:] for i in range(3)]):
    print grp 

(0, 1, 2)
(1, 2, 3)
(2, 3, 4)

.:)

, zip(l[0:], l[1:], l[2:]), * .

+2

, , , , ..

l = ['a', 'b', 'c', 'd', 'e']
n = 3
m = [l[i:i+n] for i in range(len(l)-n+1)]

:

m = [['a', 'b', 'c'], ['b', 'c', 'd'], ['c', 'd', 'e']]
+2

, zip - , , :

l = range(10)

for grp in zip(l[0:], l[2:]):
   print grp

(0, 2)
(1, 3)
(2, 4)
...

, :

for grp in zip(l[0::3], l[2::3]):
   print grp 

(0, 2)
(3, 5)
(6, 8)
+2
l = ['a', 'b', 'c', 'd', 'e'] 

>>> zip(l,l[1:],l[2:])

[('a', 'b', 'c'), ('b', 'c', 'd'), ('c', 'd', 'e')]

>>> l = [chr(x+65) for x in xrange(26)]

>>> zip(l,l[1:],l[2:])

[('A', 'B', 'C'), ('B', 'C', 'D'), ('C', 'D', 'E'), ('D', 'E', 'F'), ('E', 'F', 'G'), ('F', 'G', 'H'), ('G', 'H', 'I'), 
 ('H', 'I', 'J'), ('I', 'J', 'K'), ('J', 'K', 'L'), ('K', 'L', 'M'), ('L', 'M', 'N'), ('M', 'N', 'O'), ('N', 'O', 'P'),
 ('O', 'P', 'Q'), ('P', 'Q', 'R'), ('Q', 'R', 'S'), ('R', 'S', 'T'), ('S', 'T', 'U'), ('T', 'U', 'V'), ('U', 'V', 'W'), 
 ('V', 'W', 'X'), ('W', 'X', 'Y'), ('X', 'Y', 'Z')]
+2

Another version (similar to David) is to use a slice in a generator expression:

size = 3
for grp in (l[i:i+size] for i in range(len(l)-size+1)):
    print grp

[0, 1, 2]
[1, 2, 3]
[2, 3, 4]

This version gives lists instead of tuples, if that matters.

0
source

It is my decision to avoid using rangeas required by the OP in the comment.

>>> items = ['a', 'b', 'c', 'd', 'e']
>>> n = 3
>>> [item for item in map(lambda x: items[items.index(x):items.index(x) + n], it
ems) if len(item) == n]
[['a', 'b', 'c'], ['b', 'c', 'd'], ['c', 'd', 'e']]
0
source

All Articles