r/pythonhelp • • Sep 22 '22

Lists and Indexes

So i have been trying to make a program in which the user inputs the amount of elements that they will include in a list. After that they start to input numbers to fill the list. I want to print the list elements separated in each line with their index, like for example.

user input:

>>> 5
>>> 1
>>> 2
>>> 3
>>> 4
>>> 5

output:

list[0] = 1
list[1] = 2
list[2] = 3
list[3] = 4
list[4] = 5

I have not been able to achieve this since apparently I cant print two different things in the same print, i have used sep= '\n' to separate list elements but i cant add their index. Help would be appreciated. Thanks!

2 Upvotes

3 comments sorted by

1

u/DaaxD Sep 22 '22 edited Sep 22 '22

How are you reading the user inputs? Are you using the input function already?

value = input(">>> ")

You apparently want to do this for 5 times. For that, you need a for loop, that reads the value for 5 times.

Also, you wanted to store the values in a list, yes? You can do that by using a method called append

my_list = []
# For loop which will loop for 5 times
for i in range(5):
    # For 5 times, we read a value
    value = input(">>> ")
    # ... and store each value to the list using append
    my_list.append(value)

You can also use loops, to loop through lists and go through each element in a list

for item in my_list:
    print(item)

Or we can do the same by using the len() to determine the length of the list.

I'm also going to use fstrings, to make printing more clean.

for index in range(len(my_list)):
    print(f"my_list value in [ {index} ] is {my_list[index]}")

1

u/LaundryyBasket Sep 22 '22

Thank you so much you solved my question !

1

u/carcigenicate Sep 22 '22

Have you learned about loops? You can use a loop to call print multiple times.

And there is a way to give multiple elements to print, but it involves a few more advanced topics.