l.append[i], object is not subscriptable?

2019-02-23 18:10发布

When I do:

l = []
for i in range(10):
    if i%3 == 0 or i%5 == 0:
        l.append[i]
print sum(l)

I get

Traceback (most recent call last):
  File "PE1.py", line 4, in <module>
    l.append[i]
TypeError: 'builtin_function_or_method' object is not subscriptable

Is there really no way append all the i's that pass the condition?

2条回答
Root(大扎)
2楼-- · 2019-02-23 18:36

append is a method, you use function call syntax.

l.append(i)

Also, more elegant approach in cases like this is to use list comprehension:

l = [i for i in range(10) if i % 3 == 0 or i % 5 == 0]
查看更多
冷血范
3楼-- · 2019-02-23 18:54

l.append[i]

Wrong parenthesis.

查看更多
登录 后发表回答