PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, September 15, 2022

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

 September 15, 2022     for-loop, list, printing, python     No comments   

Issue

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:

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


Answered By - nicholas5538
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing