Narendran S Nair
Narendran S Nair

Reputation: 13

How to access the next item of a list, inside the (for item in list) loop ? (Python 3)

Imagine an imaginary list

for item in list: 
    print(item)      
    print(_________) # Fill the blanks to print next item in list

I would seek a code that replaces only the blank of the above code to print next item on list.

Upvotes: 0

Views: 141

Answers (4)

Alain T.
Alain T.

Reputation: 42143

You could use zip:

for item,nextItem in zip(list,list[1:]+[None]): 
    print(item)      
    print(nextItem)

Upvotes: 2

Matthias
Matthias

Reputation: 13222

This code will only work if there are no duplicate entries in the list. I changed the name of the list to data because it's a bad idea to overwrite the name of the builtin list (and even if it's an example I can't force myself to do that).

data = ['A', 1, 'B', 2, 'C']
for item in data: 
    print(item)      
    print(data[data.index(item) + 1])

At the moment this code crashes for the last element because it tries to access the element after the last. You could fix that by replacing the line with print('' if data.index(item) + 1 == len(data) else data[data.index(item) + 1]).

I hope that the question is about homework or something like that, because noone would/should write code like this in real production.

Upvotes: 0

timhealz
timhealz

Reputation: 94

for i,item in enumerate(list):
    if i < len(list)-1:
        print(list[i])
        print(list[i+1])

Upvotes: 2

James Paul
James Paul

Reputation: 21

I'd recommend enumerating and then using the index to access the next one. You'll need to guard against out of range.

for idx, val in enumerate(lst):
    print(val)
    print(list[idx+1])

Upvotes: 0

Related Questions