Search for element in list of list Python
<p>New to programming.
I'm trying to create a program that has a list o list (As a data base) the first element being an invoice, the second the value of that invoice and the third, the margin of income. Given an invoice (input), it will search within the list o lists(data base).</p>

<p>I currently have:</p>

<pre><code>Data_base= [["f1",2000,.24],["f2",150000,.32],["f3",345000,.32]]
invoice = input("Enter invoice: ")

if invoice in data_base :
    print ("Invoice is valid")

else :
    print("Invoice does not exist, enter a valid document: ")
</code></pre>

<p>When I run the program and I enter a valid element within the list, it does not recognize as an element within the list.</p>

<p>What am I doing wrong?</p>

<p>What is the code to be given the index if the element is within the list of lists?</p>

<p><code>in</code> keyword in Python is used to check the membership of an element in a <code>iterator</code>. That is each element of the <code>iterator</code> is checked with the operand and returns True if the operand exists in the <code>iterator</code>.</p>

<p>The <code>in</code> keyword is specifically looking for invoice in data_base which is a list. Now, it is a different story that each element of this list is another list.</p>

<p>The line <code>if invoice in data_base :</code> does the following,
Say the user input was "f1"
now "f1" is compared to the list <code>["f1",2000,.24]</code>
that is </p>

<p><code>"f1" == ["f1",2000,.24]</code> which is False, you are assuming this should return <code>True</code> but it does not, since string "f1" is not equal to the list <code>["f1",2000,.24]</code>.</p>

<p>then </p>

<p><code>"f1" == ["f2",150000,.32]</code> which is False</p>

<p>and finally </p>

<p><code>"f1" == ["f3",345000,.32]</code> which is also False.</p>

<p>You are essentially comparing the invoice(user input) to the whole element instead of just the first element of the element.</p>

<p>This program should give you the correct output. </p>

<pre><code>Data_base= [["f1",2000,.24],["f2",150000,.32],["f3",345000,.32]]
invoices_db = [ele[0] for ele in Data_base]
invoice = input("Enter invoice: ")
if invoice in invoices_db :
    print ("Invoice is valid")
else :
    print("Invoice does not exist, enter a valid document: ")
</code></pre>

<p>For more details refer the answer on <a href="http://stackoverflow.com/questions/19775692/use-and-meaning-of-in-in-an-if-statement-in-python">Use and meaning of &quot;in&quot; in an if statement in python</a></p>

python list search element