Python IF IN statement with list

list comprehension || python
nested if else in list comprehension python
python list
python list comprehension multiple variables
python list construction if else
if and for in list
nested list comprehension python
if else in list iterator python

Could I get a little help on what I'm sure's a simple solution. I've looked around here and online and not been able to solve it. I'm less than a week old in to this and have basically set myself a little task to learn some of the basics.

import pandas as pd

df1 = pd.read_csv('booking.csv', names=['snum','booked','name'])
df1.drop(['booked', 'name'], axis=1, inplace=True)

df2 = df1.values.tolist()

print('The following tickets are available; %s' % df2)
tic = input('Which ticket would you like to buy? ')

if tic in df2:
    print('Ok')
else:
    print('Ticket Unavilable')

The problem I'm having is with the If statement. No matter what value I use as the input I always get the message 'Ticket Unavailable'. I belive the error must lie with the list that has been coverted from the dataframe.

So far I've;

  • Tested the IF statement aggainst a List that hasn't been converted or imported and that worked as expected
  • 'Printed' the df2 variable type to confirm it is a list
  • The df2 variables appear in the printed question so I know they've been imported and converted across ok
  • Copy and pasted in to a different Python file with the same result

The variables are basic seat numbers A1, A2, A3, A4, A5, B1, B2, B3, B4, B5. I'm aware an input of 'A' 'B' ect would also return 'OK', the practicality isn't as important as functionality.

pd.DataFrame.values.tolist gives a nested list.

pd.Series.values.tolist gives a non-nested list, assuming your series elements are not themselves lists.

To understand what's happening here, you need to appreciate that NumPy arrays are used internally by Pandas. The values attribute of pd.DataFrame and pd.Series objects extracts corresponding NumPy array. For a dataframe, this will always be 2-dimensional, even if your dataframe has a single series.

The allowance for nested lists is clear in the NumPy docs:

ndarray.tolist()

Return the array as a (possibly nested) list.

Your have a couple of options:

pd.Series.values

For an isolated membership check in a series, you can use pd.Series.values:

vals = df1['snum'].values

if tic in vals:
    # do something
set

This uses O(1) lookup and is recommended if you will be repeatedly checking for membership in a single series:

snum_set = set(df1['snum'])

if tic in snum_set:
    # do something

Python List Comprehension (Syntax & Examples), The general Python syntax for a simple if statement is. if condition : numbers from an arbitrary list of numbers in a function with the following heading. Read the  python list list-comprehension if-statement. Share a link to this question. improve this question. edited Dec 26 '11 at 15:32. 46 silver badges. 89 bronze badges. asked Dec 10 '10 at 6:45. 152 silver badges. 175 bronze badges. marked as duplicate by Dan D. python. Users with the python badge can single-handedly close python questions as

It looks like pandas.DataFrame.values.tolist does not produce what you think it does:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame.from_records([dict(a=1), dict(a=2)])

In [3]: df
Out[3]: 
   a
0  1
1  2

In [4]: df.values.tolist()
Out[4]: [[1], [2]]

In your case tic is a string, but df.values.tolist() is a nested list. I guess, what you want is:

df2 = set(df1['snum'])

I've used a set, because hash-tables are more suited for lookup.

Python - If statements with lists, Python For Loops and If Statements Combined (Python for Data Science Basics These are presented in a nested Python list (“lists in a list”): Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary Module Reference Random Module Requests Module Math Module cMath Module Python How To Remove List Duplicates Reverse a String

Change

if tic in df2:

to

if any(tic in s for s in df2):

You have a list, however you are attempting to access it like a Panda Dataframe.

booking.csv

snum    booked  name
a1      no  
a2      no  
a3      no  
a4      no  
a5      no  
a6      no  
a7      no  
a8      no  
a9      no  
a10     no  
a11     no
a12     no
a13     no
b1      no
b2      no
b3      no
b4      no
b5      no
b6      no
b7      no
b8      no
b9      no
b10     no
b11     no
b12     no
b13     no

Your example with modification

import pandas as pd

df1 = pd.read_csv('booking.csv', names=['snum','booked','name'])
df1.drop(['booked', 'name'], axis=1, inplace=True)

df2 = df1.values.tolist()

print('The following tickets are available; %s' % df2)
tic = input('Which ticket would you like to buy? ')

if any(tic in s for s in df2):#df2.str.contains(tic):
    print('Ok')
else:
    print('Ticket Unavilable')

Gives the following output

The following tickets are available; [['snum'], ['a1'], ['a2'], ['a3'], ['a4'], ['a5'], ['a6'], ['a7'], ['a8'], ['a9'], ['a10'], ['a11'], ['a12'], ['a13'], ['b1'], ['b2'], ['b3'], ['b4'], ['b5'], ['b6'], ['b7'], ['b8'], ['b9'], ['b10'], ['b11'], ['b12'], ['b13']]

Which ticket would you like to buy? a1
Ok

or

The following tickets are available; [['snum'], ['a1'], ['a2'], ['a3'], ['a4'], ['a5'], ['a6'], ['a7'], ['a8'], ['a9'], ['a10'], ['a11'], ['a12'], ['a13'], ['b1'], ['b2'], ['b3'], ['b4'], ['b5'], ['b6'], ['b7'], ['b8'], ['b9'], ['b10'], ['b11'], ['b12'], ['b13']]

Which ticket would you like to buy? c2
Ticket Unavilable

3.1. If Statements, Perhaps the most well-known statement type is the if statement. (as C), Python's for statement iterates over the items of any sequence (a list or a string), in the  Example 2: Python If-Else Statement with AND Operator. In the following example, we will use and operator to combine two basic conditional expressions in boolean expression. Python Program. a = 3 b = 2 if a==5 and b>0: print('a is 5 and',b,'is greater than zero.') else: print('a is not 5 or',b,'is not greater than zero.') Output

It looks like you are not using the right DataFrame method to get the list of tickets. Use DataFrame.to_dict('records') to simplify extraction of the ticket names.

booking.csv

92747,true,Harry Potter
28479,false,Sherlock Holmes

Python code

import pandas as pd

# Load ticket list from CSV file
booking_df = pd.read_csv('booking.csv', names=['snum','booked','name'])

# Convert ticket list to a list of built-in Python dictionaries
ticket_list = booking_df.to_dict('records')

# Extract the ticket names from the list of tickets
ticket_name_set = {ticket["name"] for ticket in ticket_list}

print('The following tickets are available; %s' % ticket_name_set)
wanted_ticket_name = input('Which ticket would you like to buy? ')

if wanted_ticket_name in ticket_name_set:
    print('Ok')
else:
    print('Ticket Unavilable')

Output:

➜ python tickets.py
The following tickets are available; ['Harry Potter', 'Sherlock Holmes']
Which ticket would you like to buy? Harry Potter
Ok
➜ python tickets.py
The following tickets are available; ['Harry Potter', 'Sherlock Holmes']
Which ticket would you like to buy? Hamlet
Ticket Unavilable

Python For Loops and If Statements Combined (Data Science Tutorial), Question When using a list comprehension with an if, is it possible to have an else clause? Answer Yes, an else clause can be used with an if in a list  Python If statement allows the compiler to test the condition first and then, depending upon the result it will execute the statements. If the test condition is true then only statements with in the if statement block is executed.

4. More Control Flow Tools, The if statement says to only add those items that are not equivalent to the string '​octopus' , so the new list only takes in items from the tuple that  Check if element exist in list based on custom logic Python any() function checks if any Element of given Iterable is True. Let’s use it to check if any string element in list is of length 5 i.e.

Can an if statement in a list comprehension use an else?, expression for item in list if conditional ] variable name to use, followed by the word in the old list. if filter(i) Apply a filter with an If-statement. The power of a language like Python comes largely from the variety of ways basic statements can be combined. In particular, for and if statements can be nested inside each other’s indented blocks. For example, suppose you want to print only the positive. numbers from an arbitrary list of numbers in a function with the following heading.

List Comprehensions in Python 3, The boolean expression after the if statement is called the condition. in a sequence, so it is used with Python's sequence data types - strings, lists, and tuples. In Python, If Statement is used for decision making. It will run the body of code only when IF statement is true. When you want to justify one condition while the other condition is not true, then you use "if statement".

Comments
  • Did one of the below solutions help? If so, feel free to accept, or ask for clarification.
  • I would say it's not quite ethical to post an answer, that has been already posted 10 minutes ago without any significant difference.
  • @EliKorvigo, My explanation provides more detail and an alternative to set. I would have posted it a year after too, if I thought it would help.
  • Thanks for explaining this. I'm rather rudamentally assumed the list created with .tolist was the same as a list. I'd noticed the extra [] that aren't present with values in a 'regular' list, I suppose this it a give away of a nested list?
  • @immy yes, that means a list of lists.
  • @immy if the answer has solved your issue, you might consider accepting it.
  • Thank you for your answer, what would be the advantages of using a dictionary in this case over a set like others have mentioned? Does it make any difference in this example?
  • Using set(df1['snum']) gives the same result as what I wrote and is faster, so you should use it if you are using only the ticket name. You can come back check out my answer once you need access to more fields.