Reputation: 13
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
Reputation: 42143
You could use zip:
for item,nextItem in zip(list,list[1:]+[None]):
print(item)
print(nextItem)
Upvotes: 2
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
Reputation: 94
for i,item in enumerate(list):
if i < len(list)-1:
print(list[i])
print(list[i+1])
Upvotes: 2
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