This may be a case of confusion between behavior in python 2.x and python 3.x, as the behavior of the input function has changed. In python 2, input
would produce a tuple (12, 34)
if you entered 12, 34
. However, in python 3, this same function call and input produces "12, 34"
. Based on the parenthesis in your print
s and the problem you're having, it seems clear you're using python 3 :-)
Thus when you iterate using for i in range(len(sort_lst)):
, and then looking up the element to match using sort_lst[i]
, you're actually looking at each character in the string "12, 34"
(so "1", then "2", then ",", then " ", etc.).
To get the behavior you're after, you first need to convert the string to an actual list of numbers (and also convert the input you're matching against to a string of numbers).
Assuming you use commas to separate the numbers you enter, you can convert the list using:
sorted_int_list = []
for number_string in sort_list.split(","):
sorted_int_list = int(number_string.strip())
If you are familiar with list comprehensions, this can be shortened to:
sorted_int_list = [int(number_string.strip()) for number_string in sort_list.spit(",")]
You'll also need:
item = int(item.strip())
To convert the thing you're comparing against from string to int.
And I'm assuming you're doing this to learn some programming and not just some python, but once you've applied the above conversions you can in fact check whether item
is in sorted_int_list
by simply doing:
is_found = item in sorted_int_list
if is_found:
print ("Found it")
else:
print ("Didn't find it :-(")
Notes:
"12, 34".split(",")
produces ["12", " 34"]
, as the split
function on strings breaks the string up into a list of strings, breaking between elements using the string you pass into it (in this case, ","). See the docs
" 12 ".strip()
trims whitespace from the ends of a string