Python function sublist from input with while loop

Question:

My problem is this: Write a function, sublist, that takes in a list of numbers as the parameter. In the function, use a while loop to return a sublist of the input list. The sublist should contain the same values of the original list up until it reaches the number 5 (it should not contain the number 5).

I tinker with it and I get the question partially correct sometimes.

def sublist(x):
    a = [int(x) for x in input()]
    while x < 5:
        x = x + 1
    return(x)
Asked By: Lefteriss

||

Answers:

Try:

import itertools

def sublist(x):
    return list(itertools.takewhile(lambda n: n != 5, x))

Update: If this is a homework question, my answer won’t work for you – but nor should we just give you an answer, so, look at while and break. Think about creating an empty list to start with, adding things to it until you need to stop, then returning it.

Answered By: brunns

If you are looking to write a function that takes every element of a list until the number 5 (e.g [1, 2, 3, 4, 5] -> [1, 2, 3, 4]) then you could do that like this:

def sublist(input_list):
    output_list = []
    index = 0
    while index < len(input_list):
        if input_list[index] != 5:
            output_list.append(input_list[index])
            index += 1
        else:
            break
    return output_list

The while loop is broken when you reach 5. Until then, each value is added to a new list which is then returned by the function.

Update: Change while condition to check index is less than the length of the input list

Answered By: LucasGracia

It seems like you don’t understand the question.

Write a function, sublist, that takes a list of numbers as the parameter.

This means that if we have this:

def sublist(x):
    pass

then x is going to be a listnot, as in your example, a number. Also, you don’t need to do anything with input(); you’ve already got the list, so don’t need that line at all.

In the function, use a while loop to return a sublist of the input list.

Well, Python has a feature called “generators” that let you do this very easily! I’m going to cheat a bit, and not use a while loop. Instead, I’ll use a for loop:

def sublist(x):
    for num in x:
        if num == 5:
            # we need to stop; break out of the for loop
            break
        # output the next number
        yield num

Now this code works:

>>> for num in sublist([3, 4, 2, 5, 6, 7]):
...     print(num)
3
4
2
>>> 

However, sublist doesn’t technically return a list. Instead, let’s use some MAGIC to make it return a list:

from functools import wraps
return_list = lambda f:wraps(f)(lambda *a,**k:list(f(*a,**k)))

(You don’t need to know how this works.) Now, when we define our function, we decorate it with return_list, which will make the output a list:

@return_list
def sublist(x):
    for num in x:
        if num == 5:
            # we need to stop; break out of the for loop
            break
        # output the next number
        yield num

And now this also works:

>>> print(sublist([3, 4, 2, 5, 6, 7]))
[3, 4, 2]
>>>

Hooray!

Answered By: wizzwizz4

If you want to use a while loop with a check on the number value, you’d better create a generator from the input list and use next() to iterate over it:

def sublist(x):
    sub = []
    x = (num for num in x)  # create a generator
    num = next(x, 5)  
    while num != 5:
        sub.append(num)
        num = next(x, 5)  # iterate
    return sub

x = [1, 3, 4, 5, 1, 2, 3]
sublist(x)

>>> [1, 3, 4]
Answered By: Lante Dellarovere

num = [1, 2, 3, 17, 1, 3, 5, 4, 3, 7, 5, 6, 9]
new = []
def check_nums(x):
    idx = 0
    while idx < len(x) and x[idx] != 7:
        print(idx)
        new.append(x[idx])
        idx += 1
    print(idx)
    return new
print(check_nums(num))

Answered By: Alexander
def sublist(x):
    accum = 0
    sub = []
    while accum < len(x):
        if x[accum]== 5:
            return sub
        else:
            sub.append(x[accum])
        accum = accum +1
    return sub

x = [1, 3, 4, 5,6,7,8]
print(sublist(x))
Answered By: Neil Jolly
def sublist(lst):


    output_list = []
    for i in lst:
        while i==5:
            return output_list
        output_list.append(i)
    return output_list
Answered By: Harshil Zinta

I did this like that.

def sublist(x):
    count = 0
    new = []
    if 5 in x:
        while(x[count] != 5):
            new.append(x[count])
            count += 1
        return new
        
    else:
        return x
Answered By: Plabon Kumer
def sublist(a):
    i=0;
    lst=[];
    while(i<len(a) and a[i]!=5):
        lst.append(a[i]);
        i+=1;
    return lst;
Answered By: Krishna
def sublist(num):
    list = []
    for x in num:
        if x == 5:
            break
        while x != 5:
            list.append(x)
            break
    return list

num = [1,2,4,6,7,8,9,5,1,3,4]
print(sublist(num))
Answered By: Melv's
  def sublist(lst):
    sub = lst
    for i in lst:
       if i == 5:
          x = lst.index(i)
          sub = lst[:x]
    return sub

  list3 = [1,56,34,2,3,1,4,5,5,5]
  sublist(list3) 

I want to give an answer with using slicing and index method. that’s very useful for Python beginners.

Answered By: Sefa_Kurtuldu
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.