1

I am trying to generate a new list which is a subset of a given list, between the specified start index and the end index - 1. I am confused on what I am doing wrong because I keep getting empty brackets.

For example, when I start a REPL in python. Given a list

>>> a_list = [10, 20, 30, 40]
>>> sub(a_list, 1, 3)
[20, 30] 

I want the output to look like the above.

How do I accomplish this?

Here is my code right now.

def sub(new_list: list[int], start: int, end: int) -> list[int]: 
    """Generate a list which is a subset of the given list."""
    a_list: list[int] = list()
    i: int = 0
    while i < len(new_list):
        if i <= start and end <= i:
            a_list.append(i)
        i += 1
    return a_list

Thank you!

  • 1
    It should be `start <= i and i < end`.(From the example you give, it seems you don't want to include the last element.) – keineahnung2345 Feb 23 '22 at 01:42
  • 1
    Fwiw, Python lets you do this with `a_list[start:end]`. Writing this function is great for educational purposes, so if you're doing this to learn, then by all means continue. But if you just need to get the job done (for instance, if your goal is something larger), then you can use the `[]` syntax directly. – Silvio Mayolo Feb 23 '22 at 01:43
  • Just do `a_list[1:3+1]`, there's no need to declare a function. Or to do iterative-append in a loop. (Note how we have to add +1 to the RHS index; Python uses left-closed, right-open convention). – smci Feb 23 '22 at 01:45
  • @SilvioMayolo yes! I am trying to do just that. – island_girl99 Feb 23 '22 at 01:49
  • @keineahnung2345 I did that but I am not getting the a_list values that match the start and end index value. – island_girl99 Feb 23 '22 at 01:49
  • @keineahnung2345's suggestion seems right to me. What output are you getting with that fix in mind? Looks like it should work. (No idea why this question was dup-flagged, given that the point is to write the function and specifically *not* to use the built-ins) – Silvio Mayolo Feb 23 '22 at 01:51
  • @island_girl99 @silvio-mayolo Sorry for late reply. Besides `start <= i and i < end`(note that it's `i – keineahnung2345 Mar 24 '22 at 07:30

0 Answers0