3/8 String index out of range

Screen Link:
Basics.ipynb (4.1 KB)

My Code:

> from csv import reader
> opened_file = open('hacker_news.csv')
> read_file = reader(opened_file)
> hn = list(read_file)
> for row in hn[:5]:
>     print(row)
>     
> headers = row[0]
> hn = row[1:]
> print(headers)
> for row in hn:
>     print(row)
>     
> ask_posts = []
> show_posts = []
> other_posts = []
> 
> for row in hn:
>     title = row[1]
>     if title.lower().startswith('ask hn'):
>         ask_posts.append(row)
>     elif title.lower().startswith('show hn'):
>         show_posts.append(row)
>     else:
>         other_posts.append(row)
>         
> print(len(ask_posts))
> print(len(show_posts))
> print(len(other_posts))

What I expected to happen:
my code should show length of these three lists: ask_posts , show_posts , and other_posts

What actually happened:

IndexErrorTraceback (most recent call last)
<ipython-input-3-f569afc6fc95> in <module>()
     17 
     18 for row in hn:
---> 19     title = row[1]
     20     if title.lower().startswith('ask hn'):
     21         ask_posts.append(row)

IndexError: string index out of range


Click here to view the jupyter notebook file in a new tab

hey @MiloBogdanovi

why have you referenced to “row” in these lines instead of hn?

headers = row[0]
hn = row[1:] 

Don’t you think it should be:

headers = hn[0]
hn = hn[1:] 

Try that and let us know if it worked or if it still didn’t. Also why are you writing the entire code in one cell :thinking:?

2 Likes

Hi Rucha, you got it right. I’m negligent I guess.