data = ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff', 'ggg', 'hhh', 'iii', 'jjj'] this works way want work.
i = 0 print in range(len(data) - 1): print data[i] + ' ' + data[i + 1] the below code not work. there way make work enumerate or above solution simplest/best way?
print i, d in enumerate(data): print d + ' ' + d[i + 1] # indexerror: string index out of range or there way access 2 elements @ time?
in enumerate function, i represents index position of list elements , d represents value of element present @ i th index position. so, when doing d[i+1] , slicing d variable.
when value of i equals last element of data variable in enumerate block, accessing i+1th element in data i.e., data[i+1] throw index error (since i+1 th element not exist in data ) . since, want use both i , i+1 elements simultaneously, using enumerate alone may not solve problem completely. if keen on using it, have change code
for i,d in enumerate(data): if < (len(data) - 1): print d + ' ' + data[i+1]
Comments
Post a Comment