225k views
1 vote
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).

1 Answer

4 votes

Answer:

Following are the code to this question:

def sublist(l):#defining a method list sublist that accepts a list

val=[]#defining an empty list

x=0#defining x variable that store value 0

while(x<len(l)):#defining loop that check x is lessthen list length

if(l[x]==5):#defining if block that checks list value equal to 5

break#using break keyword

val.append(l[x])#add value in val list

x+= 1#increment the value of x variable by 1

return val#return val

l=[3,4,7,8,5,3,2]#defining list l

print(sublist(l))#using print method to call sublist method

Output:

[3, 4, 7, 8]

Step-by-step explanation:

  • In the above python code, a method "sublist" is declared that accepts a list, inside the method an empty list "val" and an integer variable x is defined that stores "0" value.
  • In the method, a while loop is declared that checks list length and define if block to checklist element value equal to "5". which the condition is true it will return before values.
  • In the last step, a list "l" is declared that holds value and used the print method to call sublist to prints its return value.