array=[]
for i in range(5):
array=input("Enter a number")
print(array)
I need to ask the user to input 5 numbers and then store them within a list, at the end I have to reverse it.
array=[]
for i in range(5):
array=input("Enter a number")
print(array)
I need to ask the user to input 5 numbers and then store them within a list, at the end I have to reverse it.
To add an element at the end of the list you have to use .append
method.
try this.
array=[]
for _ in range(5):
array.append(input()) # use int(input()) to so that you have int type elements
print(array[::-1]) # to print array in reverse order.
You can use list comprehension here.
[input() for _ in range(5)][::-1] # use int(input()) to so that you have int type elements
You are looking for input() function, append() method of list. See this answer to know how to reverse a list.
Try this:
array = []
num = int(input("Enter the length of array: ")) # You need to convert str returned by input to an int using int() constructor
for i in range(num):
array.append(input("Enter a number: ")) # You need to use append() method of list
print(array)
print(array[::-1])
Or
Using list comprehension:
array = [input("Enter a number: ") for i in range(int(input("Enter the length of array: ")))]
To reverse a list, use
print(array[::-1])