0

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.

1
  • 2
    Check out the itertools recipe for pairwise. Commented Apr 21, 2020 at 17:41

4 Answers 4

2
for i,item in enumerate(list):
    if i < len(list)-1:
        print(list[i])
        print(list[i+1])
Sign up to request clarification or add additional context in comments.

Comments

2

You could use zip:

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

Comments

0

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.

2 Comments

lol nope, it's just a question that popped up in my mind, I expected something like this, thanks alot for your effort (and list = data). I guess we can duplicate the list and loop on it, removing the item after each iteration to avoid the problem of duplication.
I'm so glad you told me that. :)
0

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.