1
votes

I am trying to run a python code and this seems to cause error. Please help me

def randomPlace(b,lis):
    pos = []
    for i in lis:
        if available(b,i):
            pos.append(i)

    if len.pos() != 0:
        return random.choice(pos)
    else:
        return None

b is a list with 10 characters and lis is a list with 4 integers Error is:

Traceback (most recent call last):

File "D:\TestsPython\TicTacToe.py", line 65, in randomPlace if len.pos() != 0: AttributeError: 'builtin_function_or_method' object has no attribute 'pos'

2
Did you mean len(pos)? - Ashwini Chaudhary
Oh , I feel so stupid, thank you, it worked - Pavan Padubidri

2 Answers

1
votes

The expression len.pos() asks the interpreter to locate len (the standard built-in function), look up its pos attribute (clue: it doesn't have one) and that call that looked up result. You actually want to apply the len function to the value of pos, and should therefore code

if len(pos) != 0:

Since len always returns an integer result, you could abbreviate this to

if len(pos):

Remembering, however. that empty containers evvaluate False in a Boolen context and non-empty containers evaluate True, it's usual to shorten this to

if pos:
1
votes

Use len(pos).

In order to find the size of list in python, the syntax is len(your_list).

In your case len function is not even required. You may simply do:

if pos:
    return random.choice(pos)
else:
    return None

Because if your list will have any element, if will consider it as True. In case of empty list, it will be treated as False.