简体   繁体   中英

How do I use a variable to find the position of an element in a list in Python?

I am trying to use name as a variable to capture input from the user, but **actual name of list**.index[] doesn't seem to work if I were to put a variable into its brackets.

Name of list: nameList

Name of variable: name

nameList = ['Tom', 'Joe', 'Mary', 'John', 'Bob', 'Jane']
name = input('Enter name to search :')
nameList.index[]
print('Name', name, 'is found in position', nameList[name], 'in the name list.')

How do I get around this issue?

The comments pretty much answer the question. To be more elaborate, this is how you do it:

nameList = ['Tom', 'Joe', 'Mary', 'John', 'Bob', 'Jane']
name = input('Enter name to search :')
print('Name', name, 'is found in position', nameList.index(name), 'in the name list.')

However, note that this will throw an error if the name is not present in the list. To avoid that, you should check if the name is present in the list.

nameList = ['Tom', 'Joe', 'Mary', 'John', 'Bob', 'Jane']
name = input('Enter name to search :')
if name in nameList:
    print('Name', name, 'is found in position', nameList.index(name), 'in the name list.')
else:
    print ("Name not present in nameList.")

Please do the following task as this method.

nameList = ['Tom', 'Joe', 'Mary', 'John', 'Bob', 'Jane']
name = input('Enter name to search :')
req_index =0
for item in nameList:
  if(item==name):
    break
  req_index=req_index+1

print('Name', name, 'is found in position', req_index, 'in the name list.')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM