Question

I am new to Python and this is my code:

  def f(n):
      return (n%2 != 0)


 def square (n):
      return (n*n)

 def applyif(list):
      filter(f, list)
      square(list)
      print(list)

User inputs a list, this list is being filtered with f(n) and then , if the filter applies , the odd elements in the list are squared. Unfortunately, I get this error:

Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
 applyif[1,2,3,4]
 TypeError: 'function' object is not subscriptable

I would appreciate it , if someone could figure out , what I did wrong.

EDIT: Changed code to this:

def f(x):
   return (n%2 != 0)

def square (n):
    for i in n:
       n[i] = n[i]*n[i]
    return n

def applyif(lst):
   xyz = []
   xyz = filter(f,lst)
   print(xyz)

I am getting this error when I call

 applyif([1,2,3,4]) :


 <filter object at 0x028D2C30>
Was it helpful?

Solution 2

Don't name your variable list and do applyif([1,2,3,4]) instead of applyif[1,2,3,4]

def applyif(lst):
    filter(f, lst)
    square(lst)
    print(lst)

applyif([1,2,3,4])

OTHER TIPS

You're calling it like this:

applyif[1,2,3,4]

This is a syntax error, you need to call it like:

applyif([1,2,3,4])

Additionally, you are computing the results of applying your two functions, and then throwing it away. You need to rebind your variable to the returned result.

  li = filter(f, li)
  li = square(li)

(don't name local variables list)

You could further just write your function as

print list(map(square, filter(f, li))) # assuming python 3, drop the `list` call in py2

or

print [square(x) for x in li if filter(x)]

Use applyif([1,2,3,4]) instead of applyif[1,2,3,4] as suggested above. Additionally, you are going to run into trouble with your function square(n).

Square currently takes an integer and returns an integer. You are passing a list to it though. Consider changing your code as follows:

edit:

def f(x):
    return (x%2 != 0)

def square (n):
    for i in range(0,len(n)):
       n[i] = n[i]*n[i]
    return n

def applyif(lst):
    print(list(filter(f,square(lst))))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top