Homework 1: for k in range(len(p[i])) ?

Sebastian uses the following in his code. I don't understand the len(p[i]) and Python doesn't seem to either as you can see from the 'Typeerror' it gives below. len(p) makes sense but what is len(p[i])? Seems like it would always be zero. (Sorry if it's a dumb question. I'm struggling to learn Python along with this class :)

p=[0,0,0,0]
for i in range(len(p)):
print i
print(" ")
for k in range(len(p[i])):
print k

0

Traceback (most recent call last):
File "<pyshell#84>", line 4, in <module>
for k in range(len(p[i])):
TypeError: object of type 'int' has no len()

asked 01 Mar '12, 00:36

Danno's gravatar image

Danno
1113
accept rate: 0%

edited 06 Mar '12, 22:22

jimgb-2's gravatar image

jimgb-2
7.3k3077148


5 Answers:

if p is a list of lists, the p[i] returns the ith list, which is itself a list and has a length.

link

answered 01 Mar '12, 00:37

Chris%20O's gravatar image

Chris O
8963611

len(p[i]) only works if p is a 2D list. In other words, p[i] must itself be a list to have a length.

Try replacing p with this:

p = [[1,2], [3,4], [5,6], [7,8]]
link

answered 01 Mar '12, 00:38

Matt%20Bell's gravatar image

Matt Bell
2.1k31342

p is an array of rows.

len(p) is the number of rows in the row p.

p[1] is an array of elements (columns) in the row.

len(p[1]) is the number of columns in the matrix p.

link

answered 01 Mar '12, 00:39

hughes's gravatar image

hughes
816

edited 01 Mar '12, 00:39

Since p is a list of lists, len(p[i]) is the length of row i. Since you're defining p as a simple list it won't work. Try it for p=[[0,0],[0,0]]

link

answered 01 Mar '12, 00:39

Adam%20Sherwin's gravatar image

Adam Sherwin ♦♦
17.9k2176125

Doh! Of course! Thank you all! Now back to my Python book ...

link

answered 01 Mar '12, 00:58

Danno's gravatar image

Danno
1113

Your answer
Question text:

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "Title")
  • image?![alt text](/path/img.jpg "Title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Tags:

×5,185
×97

Asked: 01 Mar '12, 00:36

Seen: 356 times

Last updated: 01 Mar '12, 00:58