0

I have a list:

a=['a1','a2','a3','a4']

and want to get adjacent list entries in following order such as

a1 a2
a2 a3
a3 a4

I tried following but its not working.

for i,b in enumerate(a):
    w1=i[i]
    w2=i[i+1]
    print w1,w2

Any suggestion?

Ibe
  • 5,615
  • 7
  • 32
  • 45
  • This is not a duplicate, because the other question asked for an iterator in a more complex scenario. This question allows the simple solution `for window in zip(a, a[1:])`. – Chronial Dec 22 '13 at 02:54
  • There is also this: [Python looping: idiomatically comparing successive items in a list](http://stackoverflow.com/q/2152640) and [Python split string in moving window](http://stackoverflow.com/q/7636004) many more. – Martijn Pieters Dec 22 '13 at 03:02

3 Answers3

2

Different alternatives:

Loop over indices up to the length minus 1:

for i in xrange(len(a) - 1):
    print a[i:i+2]

or zip together the list and a slice of the list past the first index:

for window in zip(a, a[1:]):
    print window

or zip together the list plus an iterator over the list, advanced one step:

a_iter = iter(a)
next(a_iter)
for window in zip(a, a_iter):
    print window
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

Here is a generic solution

def get_entries(a, size):
    return [a[i:i+size] for i in range(len(a) - (size - 1))]

a = ['a1','a2','a3','a4']
for i in range(1, 5):
    print get_entries(a, i)

Output

[['a1'], ['a2'], ['a3'], ['a4']]
[['a1', 'a2'], ['a2', 'a3'], ['a3', 'a4']]
[['a1', 'a2', 'a3'], ['a2', 'a3', 'a4']]
[['a1', 'a2', 'a3', 'a4']]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0
[(a[i],a[i+1]) for i in range(0, len(a) - 1)]

Your code contains the symbol

i[i]

Probably a typo, which will not execute because in your code i is an integer. A slight modification makes the original code work:

for i in range(len(a)-1):
    w1=a[i]
    w2=a[i+1]
    print w1,w2
James King
  • 6,229
  • 3
  • 25
  • 40