Home > Software engineering >  How to return all the indexes of a list inputted by the user with this function?
How to return all the indexes of a list inputted by the user with this function?

Time:08-03

With this code I expect to get an output of what the user is introducing in the console in numbers_x to get iterated by the function below, but the output only returns me the last element of the expected list, how can I get all the indexes of the list?

def listas(n):
    lst = []
    for i in range(0,n):
         elementos = int(float(input(f"Enter your number {i 1}:    ")))
    list(lst)
    lst.append(elementos)
    print(type(lst))
    return lst


numbers_x = listas(n=(int(input("Enter the total numbers of your list: "))))

print(numbers_x)

##Output##

Enter the total numbers of your list: 4
Enter your number 1:    1
Enter your number 2:    2
Enter your number 3:    3
Enter your number 4:    4
<class 'list'>
[4] #I expect that the output here, was [1,2,3,4]

CodePudding user response:

you were appending items to the list at the wrong point in the code. Remember, the for loop runs n number of times, and EACH time the user puts a number input in you have to add that to the list before the next item in the for loop runs:

def list_input_retrieval(n):
    my_list = []
    for i in range(0, n):
        print('got to for loop: i is {index}'.format(index=i))
        elements = int(float(input(f"Enter your number {i 1}:    ")))
        my_list.append(elements)
    return my_list



input_list = list_input_retrieval(5)

print(input_list)

Notice doing both int and float at the same time is redundant, since your function doesn't round numbers as expected. You could remove float and I think it would work the same:

$ python3 script.py 
Enter your number 1:    5.6
Enter your number 2:    7.6
Enter your number 3:    5.2
Enter your number 4:    6.8
Enter your number 5:    8.9
[5, 7, 5, 6, 8]

CodePudding user response:

You can try this:

def listas(n):
    return [float(input(f"Enter your number {i 1}: ")) for i in range(n)]


numbers_x = listas(int(input("Enter the total numbers of your list: ")))

print(numbers_x)

It will ask the user for n of list element and pass it the value to function listas. The user will input the value of lista based on n numbers using list comprehension and the numbers_x will return the value of listas

Output:

Enter the total numbers of your list: 3
Enter your number 1: 2.3
Enter your number 2: 1.3
Enter your number 3: 2.1
[2.3, 1.3, 2.1]

Process finished with exit code 0
  • Related