Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Search List
#4
The first issue with your code is that you compare a string against an integer. The input() is always a string so you have to convert it to an integer.

Checking for an element in a list is simple: if element in list
In [1]: listA = [1, 3, 99, 58, 22, 77, 8, 2]

In [2]: x = int(input('Give me a number: '))
Give me a number: 14

In [3]: if x in listA:
   ...:     print(listA.index(x))
   ...: else:
   ...:     print(-1)
   ...:     
-1

In [4]: x = int(input('Give me a number: ')) # here the string returned from the input is converted to an integer
Give me a number: 22

In [5]: if x in listA: # pure English :D I love Python!
   ...:     print(listA.index(x)) # get the index of the first x in the list
   ...: else:
   ...:     print(-1)
   ...:     
4
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply


Messages In This Thread
Search List - by Thethispointer - Jan-19-2018, 08:25 PM
RE: Search List - by j.crater - Jan-19-2018, 08:49 PM
RE: Search List - by Thethispointer - Jan-19-2018, 08:51 PM
RE: Search List - by j.crater - Jan-19-2018, 09:58 PM
RE: Search List - by wavic - Jan-19-2018, 08:55 PM
RE: Search List - by Thethispointer - Jan-19-2018, 10:02 PM
RE: Search List - by j.crater - Jan-19-2018, 09:14 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Search Excel File with a list of values huzzug 4 1,463 Nov-03-2023, 05:35 PM
Last Post: huzzug
  search a list or tuple for a specific type ot class Skaperen 8 2,185 Jul-22-2022, 10:29 PM
Last Post: Skaperen
  Use one list as search key for another list with sublist of list jc4d 4 2,368 Jan-11-2022, 12:10 PM
Last Post: jc4d
  Search in an unsorted list amir_0402 2 22,145 Jun-04-2020, 10:25 PM
Last Post: deanhystad
  Alpha numeric element list search rhubarbpieguy 1 1,900 Apr-01-2020, 12:41 PM
Last Post: pyzyx3qwerty
  search binary file and list all founded keyword offset Pyguys 4 2,981 Mar-17-2020, 06:46 AM
Last Post: Pyguys
  Using Python to search through a list of urls jeremy 4 3,026 Dec-18-2019, 11:52 AM
Last Post: Malt
  Search a List of Dictionaries by Key-Value Pair; Return Dictionary/ies Containing KV dn237 19 7,159 May-29-2019, 02:27 AM
Last Post: heiner55
  Linear search/searching for a word in a file/list kietrichards 3 3,582 Mar-08-2019, 07:58 PM
Last Post: Larz60+
  How to iterate through a list and search for a value fad3r 2 2,997 Jan-23-2018, 02:07 AM
Last Post: fad3r

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020