List and For Loop Practice Problem 20

Screen Link: Learn data science with Python and R projects

My Code:

opened_file = open ('dq_unisex_names.csv')
from csv import reader
read_file = reader(opened_file)
info = list(read_file)

rows = info[1:]

for element in rows:
    rows.append (len(row[0]))

What I expected to happen:

What actually happened:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-207d81e88f72> in <module>
      7 
      8 for element in rows:
----> 9     rows.append (len(row[0]))
     10 

TypeError: 'int' object is not subscriptable

I saw in the answer section that they assigned row[0] to a variable called ‘name’ and then in the next line did did len(name). While I understand the logic of the suggested solution, I am wondering why can’t it work the way I tried it? I.e. without assigning it to a separate variable? Is there any logic behind it?

There are a couple of issues with your attempt and it has nothing to do with not assigning to a separate variable.

First of all, you are using row in your code without defining it anywhere else.

len(row[0])

Nowhere in your code is row defined currently. It seems that the variable row is defined by DQ somewhere in their backend. If you print out row it returns 2. That’s the source of the error since an integer is not subscriptable.

Using the correct variable name would solve half the problem.

The second issue is that you are appending the length back to rows. You need to append the length back to the same row for every iteration.

Fixing those two should resolve the error.

1 Like