0

If I have a loop for example:

for i in nums: 
    print(i) #print current item
    print(NEXT ITEM IN LIST FROM CURRENT POS)

How would I get it to print the current item and then the next item relevant to the current item?

I want it to print every first item + the next item so a list of nums 1 2 3 4 5 would print: 1 2 3 4 5 not 1 2 2 3 3 4 4 5 5

I hope it makes sense

Julian
  • 25
  • 6

4 Answers4

4

You can use enumerate:

for idx, i in enumerate(nums):
    print(i) # print current item
    if idx < len(nums) - 1: # check if index is out of bounds
        print(nums[idx+1])

Concerning your follow up question on how to handle two elements per list iteration, without repeating any elements, you can use range with a step of 2, e.g.

for idx in range(0, len(nums), 2):
    print(nums[idx])
    if idx < len(nums) - 1:
        print(nums[idx+1])
Erich
  • 1,838
  • 16
  • 20
  • Thanks mate! I edited my question to specify something extra, would you know how to correct that? – Julian Apr 20 '20 at 11:54
  • In your example you only print every element once. I don't see how this does not contradict your original question. – Erich Apr 20 '20 at 12:00
  • When I run the code on a list of nums 1 2 3 4 5 it prints as follows: ` 1 2 2 3 3 4 4 5 5 ` – Julian Apr 20 '20 at 12:02
  • That is what you should expect from the question you asked. – Erich Apr 20 '20 at 12:04
  • Yeah that is true, but how would I go about getting it to print the current element and the next element, then in the next iteration of the loop not print the current one but the one after that? so that it prints 1 2 3 4 5 but 2 at a time in each iteration? I hope it makes sense – Julian Apr 20 '20 at 12:06
  • Why are you overcomplicating this? If you want to print line after line, you just iterate through the list and print the current element. – Erich Apr 20 '20 at 12:09
  • The question in hand is just a simplified version of a bigger problem, but I asked it that way to make it easier to understand. Thanks for the help mate, sorry to be a pain – Julian Apr 20 '20 at 12:11
  • I edited my answer for this case. – Erich Apr 20 '20 at 12:33
4

You can zip through your list:

for x, y in zip(nums, nums[1:]):
    print(x, y, sep='\n')
Austin
  • 25,759
  • 4
  • 25
  • 48
0

you should use print(num[I]) for the current item and print(num[I+1]) for the next. but make sure to not access the next element when I is the length of the list.

Noah.Ehrnstrom
  • 172
  • 1
  • 12
0

You should use enumerate function

Find your answer here. There is already similar post for the mentioned issue.

Wahab Shah
  • 2,066
  • 1
  • 14
  • 19