Indentation woes


#1

I’m having a devil of time coming to grips as to when and why the compiler throws out indentation errors. Take this simple code for example for section 18/18:

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
# Add your function here

def flatten(lst):
  result = []
  for i in lst:
  	for j in i:
      result.append(i[j])
  return result


print flatten(n)

This codes gives me the error in the console:

 File "python", line 8
    result.append(i[j])
                      ^
IndentationError: unindent does not match any outer indentation level

I don’t see where the problem is. What’s wrong with my indents?


#2

lines of code which are in a for loop need additional indent:

# wrong
    for j in i:
result.append(i[j])

# right
for j in i:
    result.append(i[j])

now look at your code:

  for i in lst:
  	for j in i:
      result.append(i[j])

the line which should be in the second for loop doesn’t have enough indent/the second for loop has too much indent


#3

I’m not sure I understand. The second loop command is indented from the first. The code block of the second loop command is indented from that second loop command, making it double indented from the first loop command. So why isn’t it working?


#4

its not, the line of code which appends to result:

result.append(i[j])

should have more indent then the second for loop, given its part of the for loop body, but if we look at your code:

  	for j in i:
      result.append(i[j])

the result append line has less indent then the second for loop, this throws an error, given this can’t be


#5

OK, I think something is going on with the formatting here, because on my screen it is clearly indented beyond the “for” line:

I notice that unless I allow the interface to indent for me following colons and line breaks then I get all sorts of indent errors. If I try to make my own indents then it throws a fit.


#6

OK there is definitely something goofy going on here. Here’s what the code block from the forums looks like on my screen:

But when I copy and paste it into notepad it turns into this:
image

Anybody else run into this problem?


#7

that is how i see the code you posted:

Screenshot_2018-01-08_14-31-30

so your screen is tricking you. Not sure how, but the indent is of. Re-indent the entire thing


#8

The width of a tab character varies with editor settings. Use spaces.


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.