Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding a string to an array and giving it a numerical value

I want to add text from an input into an array and assign it a variable based on when it was added, eg if I input "bike", it would be added to the array and then it would print "Your item is number 1" and then input again a different word and it would be number 2 etc.

list = []
main = True

shop = input("Enter the shop you are visiting: ")

while main == True:
  
  choice = input("Enter your item: ")
  list.append(choice)
  print("The priority for this item is", list[-1])
  
  

This is all I have done so far, I did list[-1] not realising it would just print what was added rather than the number position it is in.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are almost there but with a couple of fixes. First, I changed the name of your list to my_list. Then I used the enumerate function to give your desired output. Try this and see that it works.

my_list = []
main = True

shop = input("Enter the shop you are visiting: ")

while main:
  choice = input("Enter your item: ")
  my_list.append(choice)
  for i,j in enumerate(my_list):
      print(f"The priority for item {j} is {i}")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading