Question

data = ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff', 'ggg', 'hhh', 'iii', 'jjj']

This works exactly the way I want it to work.

i = 0
print
for i in range(len(data) - 1):
    print data[i] + ' ' + data[i + 1]

The below code does not work. Is there a way to make it work with enumerate or is the above solution the simplest/best way?

print
for i, d in enumerate(data):
    print d + ' ' + d[i + 1] # IndexError: string index out of range

Or is there another way to access two elements at a time?

Was it helpful?

Solution

In your enumerate function, the i represents the index position of the list elements and d represents the value of the element present at the i th index position. So, when you are doing d[i+1] , you are slicing d variable.

When the value of i equals the last element of data variable in the enumerate block, accessing the i+1th element in data i.e., data[i+1] will throw an index error (since i+1 th element does not exist in data ) . Since, you want to use both i and i+1 elements simultaneously, using enumerate alone may not solve the problem completely. If you are keen on using it, you have to change your code to

for i,d in enumerate(data):
    if i < (len(data) - 1):
        print d + ' ' + data[i+1]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top