nutship
nutship

Reputation: 4924

simple defining function Python 27

I'm writing a function that squares each element in the list.

def square(num):
    for i in range(len(num)):
        square[i] = square[i] ** 2

def action():
    nums = [2, 3, 4]
    print square(nums)


action() 

It returns an error:

    square[i] = square[i] ** 2
TypeError: 'function' object has no attribute `__getitem__`.

Ideas?

Upvotes: 0

Views: 128

Answers (3)

אריק ק
אריק ק

Reputation: 1

you cant use [] for functions, its for list or dict.

def square(num):
    l= [None] * len(num)
    for i in range(len(num)):
        l[i] = num[i] ** 2
    return l

Upvotes: 0

Rushy Panchal
Rushy Panchal

Reputation: 17532

To build upon Martijn's answer:

def square(seq):
    for index in range(len(seq)):
        seq[index] = seq[index] ** 2
    return seq # this gives the output of the function

See: 'Return' in Python.

Another way to do it (using a one-liner list comprehension):

def square(seq): return [x**2 for x in seq]

For list comprehensions, see: Python List Comprehensions

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121942

Within your square function you are referring to the function as if it's a list:

def square(num):
    for i in range(len(num)):
        square[i] = square[i] ** 2

Because square is not a list, Python tries to ask it for item i with the __getitem__ method, but that doesn't exist either.

Perhaps you meant to use num instead?

def square(num):
    for i in range(len(num)):
        num[i] = num[i] ** 2

Upvotes: 1

Related Questions