Hannah
Hannah

Reputation: 137

python - if statement and list index outside of range

I have a csv file with a 1st part made up of 3 entries and 2nd part made up of 2 entries. I want to isolate the data made up of 3 entries.

i wrote the following:

filename=open("datafile.txt","r")
data_3_entries_list=[]

 for line in filename:
    fields=line.split(",")
    if fields[2] == 0:
        break
    else:
        data_3_entries_list.extend(line)

i get the error message:
if fields[2] == 0 : IndexError: list index out of range print(data_3_entries_list)

I also tried with if fields[2] is None but i get the same error. I dont understand why im getting this error?

Upvotes: 0

Views: 3254

Answers (4)

user890167
user890167

Reputation:

You're getting the error because you're trying to get the value of an index that may not exist. There's a better way to do this, though.

Instead of testing the length outright, you can also use a split to see if the index exists. A list that isn't len(a_list) >= 3 will simply return an empty list.

>>> mylist = range(3) #this list is [0, 1, 2]
>>> mylist[2:]
[2]

>>> mylist = range(2) #however THIS list is [0, 1]
>>> mylist[2:]
[]

In this way you can use the pythonic if a_list: do_work() to test if you even want to work with the data. This syntax is generally preferred to if len(a_list) == value: do_work().

filename=open("datafile.txt","r")
data_3_entries_list=[]

 for line in filename:
    fields=line.split(",")
    if fields[2:]:  ##use a split to verify that such a split yields a result
        data_3_entries_list.extend(line)

Upvotes: 0

chepner
chepner

Reputation: 531175

There is no implicit value for non-existent elements of a list; if fields only has 2 items, then fields[2] simply does not exist and will produce an error.

Check the length of the list explicitly:

if len(fields) == 3:
    break
data_3_entries_list.append(line)  # You may want append here, not extend

Upvotes: 1

xxyzzy
xxyzzy

Reputation: 588

Use len() or str.count()

for line in filename:
    fields=line.split(",")
    if len(fields) == 3:
        data_3_entries_list.append(line)

for line in filename:
    if fields.count(",") == 2:
        data_3_entries_list.append(line)

Upvotes: 2

Zuko
Zuko

Reputation: 2914

If i have a csv file like this one, then this can work out

 with open('datafile.csv', 'w') as p:
    p.write("Welcome,to,Python")
    p.write("Interpreted,Programming,Language")

 filename=open("datafile.csv","r")
 data_3_entries_list=[]

 for line in filename:
    fields=line.split(",")
    if fields[2] == 0:
        break
    else:
        data_3_entries_list.extend(line)

Otherwise you'd have to atleast show us or me how your csv file is formatted.

Upvotes: 0

Related Questions