Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

When I list the integers in a list, an extra one gets added at the end [Python]

numberlist = [1, 4, 7, 5, 6, 2, 4]

for i in numberlist:
    pos = numberlist.index(i)
    next = pos + 1
    ordering = [i, numberlist[next]]
    print(ordering)

This is the code I’m having problems with. When I run it, it’s supposed to print multiple lists containing 2 items: The value of i and the number right after it. It does that, however an extra number is added for the last iteration and there is no consistency of what number it may be, in this case the output is:

[1, 4]
[4, 7]
[7, 5]
[5, 6]
[6, 2]
[2, 4]
[4, 7]

A 7 is added at the end, and while I thought it may have been just a repetition of a number that is already in the list, if I add another value to the list,

numberlist = [1, 4, 7, 5, 6, 2, 4, 6]

The output becomes:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[1, 4]
[4, 7]
[7, 5]
[5, 6]
[6, 2]
[2, 4]
[4, 7]
[6, 2]

A 2 is added, but 2 isn’t present in the list to begin with, and I also noticed that the 6 isn’t taken into consideration, it prints the 7 again. However, if instead of a 6, I added a 3, the code would just give me an error, as it should.

  File "c:/Users/santi/Desktop/code/order/#test zone.py", line 8, in <module>
    ordering = [i, numberlist[next]]
IndexError: list index out of range

What’s happening here?

>Solution :

numberlist = [1, 4, 7, 5, 6, 2, 4]

Based on your example and your for loop, there are 7 elements in the list.

Once i is 6 which is the last position on the list, it will still carry out all the codes in the for loop. What I could suggest is to use a if condition to break the for loop when it reaches the last element in the list.

numberlist = [1, 4, 7, 5, 6, 2, 4]

for position, number in enumerate(numberlist):
    # Break for loop once it is the last position
    # Need to -1 from len() function as index position is from 0 to 6
    if position == len(numberlist) - 1:
        break
    # proceed to next position with += 1
    position += 1
    ordering = [number, numberlist[position]]
    print(ordering)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading