I have the index of an item in a list, how do i find the item of that index?

Question:

Currently, I am trying to program an encoder/decoder for a custom cipher and I have an idea of how to encrypt the data. What I am doing is I am putting the user’s message in a list, then getting the element with the index of 0, then encrypting that and printing all the characters at once. However, every site I search has the reverse problem: finding the index of an element in a list. Any ideas?

message = input()
uselist = list(message)
numofchar = len(message)
for i in range(0, numofchar):
    (code for searching the list)

(some people were confused, so here is a roadmap)
user inputs message -> message is changed to list and length is determined -> for loop is used to check the index of 0 -> character is pulled from the list and translated

Asked By: Daniel Ables

||

Answers:

What you’re asking is a bit confusing but there are two cases.

  1. You know the index and looking for the message, then you use the ordinary Python way to access list items:
    uselist[index]
  2. You know the message and you want to find its index in the list, in this case, you can use the index() method:
    uselist.index(message)

However, this method needs the message to be unique, or it will return the lowest index of its where it first occurred. And, in case the message is not found, it will raise an error.

Answered By: Important Victory
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.