-1

I have a list, somewhat similar to the one below.

lines = ['This is line 1',
'This is another line',
'This is the third line. Line 03.']

When I run the return statement to process for the len of the line,

for line in lines:
    return(len(line))

generates the following error:

File "", line 2
return(len(line))
^
SyntaxError: 'return' outside function

I can however print the lengths of the lines,

for line in lines:
    print(len(line))

Result:

14
20
32

How exactly is the return statement outside function in this instance?

Edit: Here is what it looks like in my Notebook. http://imgur.com/w4EzlrH

user2762934
  • 2,332
  • 10
  • 33
  • 39
  • 1
    where exactly have you placed that `for` loop that contains the `return`?It's either top level or you're not showing us. The `SyntaxError` is pretty descriptive, it *must* be in a function. – Dimitris Fasarakis Hilliard Feb 18 '17 at 23:54

2 Answers2

2

Your indention might be inconsistent. Use four spaces per indention level as recommended by PEP-8. Secondly, it should be inside a function. Thirdly, your return statement won't return length of all the items as you want.

vsr
  • 1,025
  • 9
  • 17
2

The return function is used to pass a value back to where a certain function is called. The way I see it, you're essentially trying to overwrite the return value. You should use it in a function that does something and returns the value back. Your loop and return statement don't appear to be in a function.

In example below I take each item in the list, pass it into the check_len function, which obviously checks length of the item and returns it. Then, the length of each item in the list is printed.

Example:

lines = ['This is line 1',
'This is another line',
'This is the third line. Line 03.']

def check_len(i):
    return len(i)

for line in lines:
    print(check_len(line))
Luke
  • 744
  • 2
  • 7
  • 23