0

I'm writing a program that takes 2 arguments, a list of numbers 1-10. and a variable of n = 6. I made a function that takes in the two arguments and returns the values that are less than 6 into a new list. But I'm trying to print the numbers that are less than 6. It's printing the index numbers. Is there a quick fix or simple way to convert the items in input_list into integers to print as a result?

it's printing [0,1,2,3,4] but I want it to print [1,2,3,4,5]

Thanks for your help!

* Python3 code *

This program takes in two arguments, a number, and a list. A function should return a list of all numbers less than the number

def main():

    #initialize a list of numbers
    input_list = [1,2,3,4,5,6,7,8,9,10]
    n = 6

    print("List of Numbers:")
    print(input_list)

    results_list = smaller_than_n_list(input_list,n)

    print("List of Numbers that are smaller than 6:")
    print(results_list)

def smaller_than_n_list(input_list,n):
    # create an empty list
    result = []

    for num in range(len(input_list)):
        if n > input_list[num]:
            result.append(num)
    return result

main()
foglerit
  • 7,792
  • 8
  • 44
  • 64
LAX2SFO
  • 11
  • 2

2 Answers2

1

you can just do:

def smaller_than_n_list(input_list, n):
    result = []
    for i in input_list: #i will be equal to 1, then, 2 ... to each value of your list
        if n > i:
            result.append(i) #it will append the value, not the index
    return result
wakonda
  • 406
  • 3
  • 6
  • Thanks for your help and assistance! – LAX2SFO Apr 01 '20 at 21:21
  • @LAX2SFO Please _do not_ add a comment on your question to say "Thank you". Comments are meant for __requesting clarification__, leaving __constructive criticism__, or __adding relevant__ but minor __additional information__, __not__ for socializing. If you want to say "thank you," then __vote on__ or __accept__ that person's answer, or simply pay it forward by _providing a great answer_ to someone else's question. – Joey Apr 02 '20 at 01:32
0

the index in python starts from 0, when you iterate over range(len(input_list)) you are accessing and storing the indices so you get [0, 1, 2, 3, 4], to fix you may use:

for item in input_lsit:
    if n > item:
        result.append(item)

in this way you are iterating over the elements from input_list and store in your list result the elements that are less than n

also, you may use a list comprehension:

def smaller_than_n_list(input_list,n):
    return [e for e in input_list if e < n]
kederrac
  • 16,819
  • 6
  • 32
  • 55