List index out of range, but list has enough elements

Discussion in 'Python' started by Costin GamenÈ›, Nov 9, 2010.

  1. Hi, I am trying to read a string as csv, but I encountered an odd
    problem. Here's my code:

    csvfile = csv.reader(datastr.split('\n'), delimiter=';')
    r = ''
    for i in csvfile:
    for j in i:
    print j
    print i[0]

    the "print j" statement works, but "print i[0]" returns "IndexError:
    list index out of range". Am I missing something?
    Costin GamenÈ›, Nov 9, 2010
    #1
    1. Advertising

  2. Costin GamenÈ›

    Peter Otten Guest

    Costin GamenÈ› wrote:

    > Hi, I am trying to read a string as csv, but I encountered an odd
    > problem. Here's my code:
    >
    > csvfile = csv.reader(datastr.split('\n'), delimiter=';')
    > r = ''
    > for i in csvfile:
    > for j in i:
    > print j
    > print i[0]
    >
    > the "print j" statement works, but "print i[0]" returns "IndexError:
    > list index out of range". Am I missing something?


    Change

    print i[0]

    to

    print i

    You'll see that there are empty rows in your data. You cannot detect these
    rows with

    for j in i:
    print j

    because you get zero iterations, i. e. the

    print j

    statement is never executed for these rows.

    Peter
    Peter Otten, Nov 9, 2010
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Corno
    Replies:
    4
    Views:
    404
    Joe Kaplan \(MVP - ADSI\)
    May 29, 2005
  2. sam
    Replies:
    8
    Views:
    514
    Tuomas
    Sep 21, 2006
  3. Replies:
    36
    Views:
    1,596
    MonkeeSage
    Oct 11, 2006
  4. Georgy Panterov

    list index out of range

    Georgy Panterov, May 13, 2008, in forum: Python
    Replies:
    2
    Views:
    400
    Mike Kent
    May 13, 2008
  5. Corno
    Replies:
    4
    Views:
    125
    Joe Kaplan \(MVP - ADSI\)
    May 29, 2005
Loading...

Share This Page