Vandan Bhardwaj
Vandan Bhardwaj

Reputation: 53

Python throwing ValueError: is not in list although it's there in list

I am populating a tuple by importing a CSV file in Python. Now when I try to get index of a value in that tuple, it gives Value error: is not in list although the value is present. Below is the code I am using along with the sample data. Following is the content of csv

IsNonPO,ApprovedState,ApprovalRecords/0/Comment,ApprovalRecords/0/Comment.Date

I am using the following code

import csv
flist = [tuple(row) for row in csv.reader(open('D:\\result_IV.csv', 'rU'))]
print (flist)
x = flist.index('IsNonPO')
print(x)

Below is the output I get

 [('IsNonPO', 'ApprovedState', 'ApprovalRecords/0/Comment','ApprovalRecords/0/Comment.Date']
File "C:/Users/abc/PycharmProjects/Default/first.py", line 10, in <module>
 x = flist.index('IsNonPO')
ValueError: 'IsNonPO' is not in list

Upvotes: 2

Views: 4575

Answers (2)

glglgl
glglgl

Reputation: 91049

You don't follow your data structure.

According to your code, what you get is a list of tuples. Each tuple represents one line, and each tuple item represents a value in the csv.

So for

IsNonPO,ApprovedState,ApprovalRecords/0/Comment,ApprovalRecords/0/Comment.Date

you should get

[('IsNonPO', 'ApprovedState', 'ApprovalRecords/0/Comment','ApprovalRecords/0/Comment.Date')]

(note the missing )after the closing ].

So indeed, the list doesn't contain the given string, but a tuple with the given string.

One approach could be

n, val = next((n, i) for n, i in enumerate(flist) if 'IsNonPO' in i)

which gives you the first item (and the tuple) which contains 'IsNonPO'.

Then you can proceed with getting the index of 'IsNonPO' in that tuple.

Of course, it depends on what you really want to achieve. If you always have only one row, yashjain12yj's answer would work as well.

Upvotes: 0

yashjain12yj
yashjain12yj

Reputation: 773

The problem here is, You are parsing CSV content in tuple and then storing that tuple in a list.

    flist = [('IsNonPO', 'ApprovedState', 'ApprovalRecords/0/Comment','ApprovalRecords/0/Comment.Date')]

So to access the first row, use flist[0]

then to get the index of a value in tuple use:

    flist[0].index('IsNonPO')

Just change line 10 to:

    x = flist[0].index('IsNonPO')

Upvotes: 4

Related Questions