Reputation: 103
I have a list with some numbers in it. The user enters the position of the item they want to print. For example:
L = [1,2,3,4]
input = 1
output = 2
So the user wants to print the number in position 1 so the output will be 2. I tried the following but it didn't work:
input = int(input("Enter position: "))
for i in L:
print(input[i])
Upvotes: 0
Views: 1345
Reputation: 2047
List is a data structure which stores data using index number. suppose you have list called
l = ['a','b','c']
Index number of 'a' is 0 , 'b' is 1 , 'c' is 2
so list[index] will give you the element at that index.
l[2] = 'b'
There for no need to use a for loop, if you already know the index number.
Upvotes: 0
Reputation: 6748
If you want to stick to the original code, try this:
L = [1,2,3,4]
input = 1
output = 2
input = int(input("Enter position: "))
for i in L:
print(L[input])
Your problem is that you indexed the input, not the list. This prints it 4 times just to let you know.
Upvotes: 0
Reputation: 1101
You could use something simple like:
chooseFrom = [1,2,3,4]
choice = int(input(">"))
print(chooseFrom[choice])
Upvotes: 0
Reputation: 3664
You don't need the for loop
L = [1,2,3,4]
input = int(input("Enter position: "))
print(L[input])
Upvotes: 0