Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Search List
#1
Hello Programmers,

I am working on learning python. This isn't for school, so we don't need to be extremely rigid, I am more interested in learning how to utilize Python as opposed to Windows/DOS batch scripts.

Today I am on:

Search an Element in an array list

https://practice.geeksforgeeks.org/probl...an-array/0

Quote:FROM
https://practice.geeksforgeeks.org/probl...an-array/0

Search an Element in an array
Show Topic Tags
Given an integer array and an element x, find if element is present in array or not. If element is present, then print index of its first occurrence. Else print -1.

Input:

First line contains an integer, the number of test cases 'T' Each test case should contain an integer, size of array 'N' in the first line. In the second line Input the integer elements of the array in a single line separated by space. Element X should be inputted in the third line after entering the elements of array.

Output:

print the output in a separate line returning the index of the element X.If element not present then print -1.

Constraints:

1 <= T <= 100

1 <= N <= 100

1 <= Arr[i] <= 100

Example:

Input:
1
4
1 2 3 4
3

Output:
2

Explanation:
There is one test case with array as {1, 2, 3 4} and element to be searched as 3. Since 3 is present at index 2, output is 2

** For More Input/Output Examples Use 'Expected Output' option **
Author: shef5

I currently have:

#Given an integer list and an element x, find if element is present in list
#or not. If element is present, then print index of its first occurrence.
#Else print -1.

listA = [1, 3, 99, 58, 22, 77, 8, 2]
instructions = '''Please input a random integer between 1 - 100,
this program will find if the element is present within the list.'''

print(instructions)
x = input()

for i, number in enumerate(listA):
    y = listA[i]
    if y == x:
        print(i)
        break

if y != x:
    print(-1)
Which generates the output:

Quote: RESTART: C:/Users/.../SearchAnElementInList.py
Please input a random integer between 1 - 100,
this program will find if the element is present within the list.
99
-1
>>>
RESTART: C:/Users/.../SearchAnElementInList.py
Please input a random integer between 1 - 100,
this program will find if the element is present within the list.
1
-1
>>>
RESTART: C:/Users/.../SearchAnElementInList.py
Please input a random integer between 1 - 100,
this program will find if the element is present within the list.
88
-1
>>>

The issue is that it is returning -1 for both valid and invalid input values. Please let me know if anyone may have some help. Thank you!
Reply
#2
The thing is that x = input() makes x variable of type string. So when you compare x == y, you are comparing strings and integers, which will always return false. So you either need to make items in your list strings as well, or cast string to integer upon entering number, like this:

x = int(input())
Reply
#3
(Jan-19-2018, 08:49 PM)j.crater Wrote: The thing is that x = input() makes x variable of type string. So when you compare x == y, you are comparing strings and integers, which will always return false. So you either need to make items in your list strings as well, or cast string to integer upon entering number, like this:

x = int(input())

Ah I see, tricky little line. Tongue TY!
Reply
#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
#5
Hehe yes, it is ;) YW.

I can comment on your code further.

When you have a for loop, your "for variable" is the item from a list (or any other iterable) you are looping over. So, you can replace this:

for i, number in enumerate(listA):
    y = listA[i]
    if y == x:
        print(i)
        break
 
if y != x:
    print(-1)
with
for i, number in enumerate(listA):
    if number == x:
        print(i)
        break
 
if number != x:
    print(-1)
And to make things even more fun (we love Python for that!!!), you can use x in listA to check if the item exists in the list (will return either true or false).

Next fun thing... if you want an index of item in list, you can use list's index method:
listA.index(22)

Now you have some material for modifying your code and exploring Python further ;)

P.S.: The lesson you can take from this is that Python has a huge amount of handy tools built in. So if you think of simple tasks such as sorting a list, finding index of an item, taking a sum/mean etc... It is most likely implemented already. And with a simple online search you will quickly get the answer you want - just give it a try ;)
Reply
#6
(Jan-19-2018, 08:51 PM)Thethispointer Wrote:
(Jan-19-2018, 08:49 PM)j.crater Wrote: The thing is that x = input() makes x variable of type string. So when you compare x == y, you are comparing strings and integers, which will always return false. So you either need to make items in your list strings as well, or cast string to integer upon entering number, like this:

x = int(input())

Ah I see, tricky little line. Tongue TY!

If unsure in such situations, you can use type(x), and it will print type of x. Pretty handy with debugging!
Reply
#7
(Jan-19-2018, 08:55 PM)wavic Wrote: 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

I am going to need to play with this one, it's a bit complicated for my skill level at this moment. I am taking on a lesson each weekday at this time, let's hope I keep it up! Cool

I successfully used:

...
x = int(input())
...
Which produced output:

Quote:Please input a random integer between 1 - 100,
this program will find if the element is present within the list.
99
2

...which is as desired!

Although, I am going to round this one out with the additional content I have yet to review in this thread. Thanks friends!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Search Excel File with a list of values huzzug 4 1,446 Nov-03-2023, 05:35 PM
Last Post: huzzug
  search a list or tuple for a specific type ot class Skaperen 8 2,173 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,334 Jan-11-2022, 12:10 PM
Last Post: jc4d
  Search in an unsorted list amir_0402 2 21,411 Jun-04-2020, 10:25 PM
Last Post: deanhystad
  Alpha numeric element list search rhubarbpieguy 1 1,886 Apr-01-2020, 12:41 PM
Last Post: pyzyx3qwerty
  search binary file and list all founded keyword offset Pyguys 4 2,958 Mar-17-2020, 06:46 AM
Last Post: Pyguys
  Using Python to search through a list of urls jeremy 4 3,013 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,111 May-29-2019, 02:27 AM
Last Post: heiner55
  Linear search/searching for a word in a file/list kietrichards 3 3,575 Mar-08-2019, 07:58 PM
Last Post: Larz60+
  How to iterate through a list and search for a value fad3r 2 2,973 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