0

This is my first time posting and I am a bit of newbie so please excuse any errors in my question. I have to create a function that uses the While loop and takes in a list of numbers and adds each number to a new list until the a specific number is reached. For example - I want each number in a list to be added until the number 5 is reached in the list. If the number 5 is not in the list, then I would get the entire list as is. The issue I am having is with this last part. My current code, posted below, can give me a new list of numbers that stops at the number 5 but I get the "List index out of range" error when the number 5 is not included in the list. I am sure its something small that I am not factoring in. Any help or guidance on what I am doing wrong would be greatly appreciated.

def sublist(x):
    i = 0
    num_list = []
    while x[i] != 5:
        num_list.append(x[i])
        i = i + 1
    return num_list

print(sublist([1, 2, 5, 7])) #works fine
print(sublist([1, 2, 7, 9])) #list index out of range error
4
  • while x[i] != 5: will be true for each element in the 2nd list so it will continue even after you've read the last element (9) Commented Jan 8, 2019 at 14:04
  • 1
    What exactly did you expect your code to do if there was no 5 in the list? You don't tell it to stop anywhere. Commented Jan 8, 2019 at 14:04
  • you can update the while condition as while x[i] != 5 and i<len(x): to avoid the out of range exception Commented Jan 8, 2019 at 14:09
  • Python rules of thumb: where possible, use for rather than manually incrementing an index inside a while. Where possible, iterate directly over the elements of a list rather than iterating over its indices. Commented Jan 8, 2019 at 14:09

4 Answers 4

1

As others have pointed out, it is best to use a for loop when you already know the number loops you need (e.g.: len(x) in your case).

If you still really want to use a while loop instead, you will need to check every loop to see if you have checked every item in the old list, and exit the loop if you do. Here's what your code could look like if you're using a while loop:

def sublist(x):
    i = 0
    num_list = []
    original_length = len(x)
    while i < original_length and x[i] != 5:
        num_list.append(x[i])
        i = i + 1
    return num_list

print(sublist([1, 2, 5, 7])) #works fine
print(sublist([1, 2, 7, 9])) #now also works fine

EDIT: I originally had the check for i < original_length inside the loop, I've changed it to be inside the while condition. BUT BE CAREFUL because the check MUST come before x[i] != 5. What I mean is that using this will work:

while i < original_length and x[i] != 5:

But this will not:

while x[i] != 5 and i < original_length:
Sign up to request clarification or add additional context in comments.

Comments

0

This should do the trick. If n (5 in your example) is in the list x it will take the list until that point. Else, it will take the whole list. This isn't the most pythonic option, though, probably someone knows a better way.

def sublist(x, n):
    num_list=[]
    if n in x:
        for i in x:
            while i!=n:
                num_list.append(i)
    else:
        num_list=x
    return num_list

Comments

0

Your loop will not stop if there is no 5 in the list, so the index i will be equal to the length of x (length of x is out of range) in the iteration when the error happens.

When looping with python, it's better to use for in loops:

def sublist(x):
  num_list = []
  for n in x:
    if n != 5:
      num_list.append(n)
    else:
      break
  return num_list

print(sublist([1, 2, 5, 7])) # [1, 2]
print(sublist([1, 2, 7, 9])) # [1, 2, 7, 9]

Comments

0

Try this

def sublist(x):
    x.sort() 
    limit_num = 5
    if limit_num not in x:return x
    return x[:x.index(limit_num)]

print(sublist([1, 2, 5, 7]))
print(sublist([1, 2, 7, 9])) 

Result:[1, 2]
       [1, 2, 7, 9]

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.