Manuel Abascal
Manuel Abascal

Reputation: 6312

Issues when running a for loop & appending the items to a empty list in Python

I would like to know what am I doing wrong with my code. I'm a JavaScript developer & I'm learning Python currently. I'm creating a function that takes a list as an argument, loops through it & appends a new list with items type string from the previous one. However, I'm getting this error SyntaxError: bad input on line 4 in main.py.

First, I would like to know what I'm doing wrong. Second, how can I fix it?

def filter_list(arr):
  results = list()

    for x in arr:
        if isinstance(x, str):
        results.append(x)
        print(results)

filter_list([1, 2, 3, "a", "b", 4])

Upvotes: 0

Views: 147

Answers (4)

Naved Ansari
Naved Ansari

Reputation: 36

def filter_list(arr):
    results = list()

    for x in arr:
        if isinstance(x, str):
            results.append(x)
        print(results)

filter_list([1, 2, 3, "a", "b", 4])

1) Make the indentaion same in line 2 and line 4. 2) indent result.append(x) after if statement.

Upvotes: 0

nolyoly
nolyoly

Reputation: 136

def filter_list(arr):

  results = list()

  for x in arr:
      if isinstance(x, str):
          results.append(x)
          print(results)

filter_list([1, 2, 3, "a", "b", 4])

Your spacing is incorrect. This code works.

Check if statement spacing. Particularly line 5 block.

  • 1 tab indent on line 5
  • 2 tab indents on line 6
  • And 3 on line 7 and 8

Indents are typically 4 spaces, you can use literal tabs but note you cannot mix tabs and spaces

Upvotes: 0

MarkAWard
MarkAWard

Reputation: 1919

As others have mentioned, your issue is with the indentation in your if statement. If your goal is to obtain a filtered list of only strings from the original list, not just printing the list you could go with:

def filter_list(arr):
    results = list()

    for x in arr:
        if isinstance(x, str):
            results.append(x)
    return results

Another alternative would be to use a functional approach that is popular in python and probably familiar coming from javascript:

results = filter(lambda x: isinstance(x, str), arr)

In the above, results will be an iterator as filter is a generator function, a function for which the results can be iterated over. If you want to get back a list, you can add list(results)

Upvotes: 1

gilch
gilch

Reputation: 11641

The indentation is incorrect. Python's blocks begin with a :, but it needs a dedent to know when they end. An empty block must have an explicit pass.

In particular, note that this if has an empty block without a pass. (The next line was not indented more, so the block must have ended.)

if isinstance(x, str):
results.append(x)

And also, within a block, indentation must be consistent. The for is an unexpected indent, because there was no starting : to allow it to be indented more.

results = list()

    for x in arr:

Upvotes: 0

Related Questions