1

The list a below prints all the items in between 0 and 5:

[1, 2, 3, 2, 3]

a = [100, 1, 10, 2, 3, 5, 8, 13, 2, 3, 55, 98]


def new_list(x):
    new = []
    for item in range(len(x)):            

        if x[item] < 5 and x[item] > 0:
            new.append(x[item])
    return new


print new_list(a)

How can I print the sub-list where the items are in between 0 and 5 inclusive, and if the item falls out of the range, start a new sub-list?

Expected output:

[1], [2,3,5], [2,3]

nilsinelabore
  • 4,143
  • 17
  • 65
  • 122

4 Answers4

1

Then you should make another list.


def new_list(x):
    new = []
    returns = []
    for item in x: # <- I modified the for loop
        if item < 5 and item > 0:
            new.append(item)
        elif len(new) > 0: # <- if out of range and new is not empty
            returns.append(new)
            new = []
    if len(new) > 0: # <- last new check
        returns.append(new)
    return returns
tomo_iris427
  • 161
  • 6
  • 1
    This will drop the last sub-list; need an extra `if new: returns.append(new)` after the `for` loop, just before the `return` statement. – Jiří Baum Nov 12 '20 at 03:32
1

I created a new list called sublist called sub to hold values that are between 0 and 5. When it comes across a number that is outside 0 and 5 it adds the sublist to the main list called new and resets the sublist to be empty

a = [100, 1, 10, 2, 3, 5, 8, 13, 2, 3, 10, 3, 1, 3, 10, 1]

def new_list(num_list):
  new = []
  sub = []

  for num in num_list:            
    if num < 5 and num > 0:
      sub.append(num)
    else:
      if len(sub) >= 1:
        new.append(sub)
        sub = []

  if len(sub) >= 1:
    new.append(sub)

  return new

print(new_list(a))
BWallDev
  • 345
  • 3
  • 13
1

That was fun. Just another try:-)

a = [1,2,100, 1, 10, 2, 3, 5, 8, 13, 2, 3, 55, 98,1,2,3,100,1]

def new_list(x):
    new = []
    sub = []
    temp = 0
    for item in x:  
        if item <= 5 and item >= 0:
            sub.append(item)
            if (temp > 5) or (temp == 0):
                new.append(sub)
        else:
            sub = []
        temp = item
    return new

print(new_list(a))
sharathnatraj
  • 1,614
  • 5
  • 14
1

Just for fun, I decide to do this with a comprehension list:

numbers = enumerate([100, 1, 10, 2, 3, 5, 8, 13, 2, 3, 55, 98])
[[starter_number] + list(next(iter(())) if n>5 else n for i, n in numbers) for  i, starter_number in numbers if starter_number<5]

I used this to see how to break inside a comprehension list https://stackoverflow.com/a/9572933/4082917

Note: This is just for fun :)

And also, using enumerate you can simplify the loop version:

numbers = enumerate([100, 1, 10, 2, 3, 5, 8, 13, 2, 3, 55, 98])
result = []
for _ , num in numbers:
    if num > 5:
        continue
    aux = [num]

    for _ , num in numbers:
        if num > 5:
            break
        aux.append(num)

    result.append(aux)
    
print(result)
Raúl Martín
  • 4,471
  • 3
  • 23
  • 42