Python Forum
Hot mess with functions, lists, and while loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Hot mess with functions, lists, and while loop
#1
The problem seems like it should be rather easy, but I'm all over the map in trying to solve it. Here it is:

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

What I have:
inputlist = [1, 2, 3, 4, 5]
def sublist (inputlist):
    sublist2 []
    count = 0
    while count < 4:
        sublist2.append(count)
        count = count + 1
I'm unclear about a number of things.
  • When they want the sublist to take in a list of numbers as the parameter, are they referring to having something like I put down, that is a sublist that imports its parameters from a separate list, in this case inputlist.
  • What call should I make for the function, if the parameters are already set?
  • Do I need a second sublist to which I can append the incremented list of integers? One to take the list of parameters and another to return a sublist of the input list.

Anyway, sorry for the mess, but I truly need help with this.
Reply
#2
it's easier to use a range for this:
>>> ilist = [1, 2, 3, 4, 5]
>>> newlist = []
>>> for n in range(len(ilist)-1):
...     newlist.append(ilist[n])
... 
>>> newlist
[1, 2, 3, 4]
>>>
Reply
#3
(Jul-14-2019, 10:05 PM)johneven Wrote: When they want the sublist to take in a list of numbers as the parameter, are they referring to having something like I put down, that is a sublist that imports its parameters from a separate list, in this case inputlist.
Yes but it can be anything in the header there as well as in the function code. You pass he actual list when you call it. It doesnt have to be the same name, but it can.

(Jul-14-2019, 10:05 PM)johneven Wrote: What call should I make for the function, if the parameters are already set?
You would call it as
sublist(inputlist)
(Jul-14-2019, 10:05 PM)johneven Wrote: Do I need a second sublist to which I can append the incremented list of integers? One to take the list of parameters and another to return a sublist of the input list.
For the record a for loop is the pythonic way. But since you need a while loop....

After your while loop header instead of appending count append the original list indexed to count
sublist2.append(inputlist[count])
Then return sublist2 and call the function with the argument.
Recommended Tutorials:
Reply
#4
Larz60-
Thanks for this other way of solving the problem, but I have to solve it in the way that the homework problem asks. (see top of first post)

metulburr-
Thanks for your point by point answers.
Reply
#5
I read your assignment differently. I read that it is to test each member of the source list for the value "5" and keep adding members from the source list to the destination list until it fails that test. So, it should also work with an input list of [7, 10, 21, 1, 5, 8] and add just the elements 7, 10, 21, and 1.
I get that from "up until it reaches the number 5" - your code would be "up until it reaches the 5th element" (great movie btw).

So, I suggest testing each element and adding that element to the second list until you reach an element with the value of 5.
Reply
#6
(Jul-14-2019, 10:05 PM)johneven Wrote: 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 understand this assignment as 'keep values until 5 (excluded)'.

If mess is hot then we should let out some steam.

Let's start with 'sizzling parameter' issue. This should clear it: What is the difference between arguments and parameters?.

Next check out while loop:

>>> help('while')
The "while" statement
*********************

The "while" statement is used for repeated execution as long as an
expression is true:

   while_stmt ::= "while" expression ":" suite
                  ["else" ":" suite]

This repeatedly tests the expression and, if it is true, executes the
first suite; if the expression is false (which may be the first time
it is tested) the suite of the "else" clause, if present, is executed
and the loop terminates.

A "break" statement executed in the first suite terminates the loop
without executing the "else" clause’s suite.  A "continue" statement
executed in the first suite skips the rest of the suite and goes back
to testing the expression.

Related help topics: break, continue, if, TRUTHVALUE
(END)
So it's 'repeated execution as long as an expression is true'.

This is nice and all but essence of the problem boils down to how to advance this repeated execution (to check all items in list). It will be quite silly wrap while loop around for loop if for itself is sufficient:

def sublist(lst):
    nums = list()
    for num in lst:
        if num == 5:
            return nums
        else:
            nums.append(num)
    else:                     # no-break
        return nums


How to advance through list without for-loop? (I personally refuse to write knowingly redundant code, even if it's an assignment Smile )

One option is to consume iterator with next():

def sublist(lst):
    iterator = iter(lst)
    nums = list()
    while iterator:
        try:
            num = next(iterator)
            if num == 5:
                return nums
            else:
                nums.append(num)
        except StopIteration:
            return nums
How professionals do it? There is built-in module itertools with function takewhile() and it's documentation provides rough 'equivalent code'. Worth of learning if interested in Python.

Same task - return all elements up to 5 (excluded) - can solved with takewhile:

from itertools import takewhile
list(takewhile(lambda x: x!=5, your_list))
If you are interested not letting Python assignments to boil over you can use built-in help at any time. For example: you can have quite a comprehensive information about functions when typing help('def') into interactive interpretator.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#7
In the first posting, the script does not actually use the input list.
The assignment writer should have clarified if you are to stop at the 5th element or the value 5, as the function cannot assume the list will simply be the sequential integers.
Using while, assuming 5 is the stop code, the following works:
def sublist(lst):
    lst2 = list()
    pointer = 0
    while lst[pointer] != 5 :
        lst2.append(lst[pointer])
        pointer += 1
    return lst2

alist = [1, 2, 3, 4, 6, 5, 8]
print (sublist(alist))
and gives the result
== RESTART: C:/Users/summersj/AppData/Local/Programs/Python/Python37/aa.py ==
[1, 2, 3, 4, 6]
Reply
#8
jefsummers and perfringo:

Thank you both for helping me understand the problem better and for the time it must have taken to come up with your comments. I agree that the list of integers was not meant to be sequential.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Python, While loop & lists jaki 1 2,183 Jun-28-2018, 11:14 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020