0

I want to get each item in the list 'spam' but i an not able to call spam list..

spam = ['apples' , 'bananas' , 'tofu' , 'cats']
i = 0
n = len(spam)


for i in range (0, n):
    if i <= n :
        print(spam(i) , end = ',')
        i += 1
    else:
        break
Traceback (most recent call last):
  File "C:\Users\admin\AppData\Local\Programs\Python\Python38\commaCode.py", line 9, in <module>
    print(spam(i) , end = ',')
TypeError: 'list' object is not callable
1
  • Did you try to convert a while loop to a for loop? You seem to have missed some crucial parts of a for loop with range. You don't need the if, you don't need to increment i manually and you don't need break. In fact, you don't even need the i. Please read the answer of @tyrion below. Commented Apr 12, 2020 at 11:15

3 Answers 3

3

As the error message points out, list objects are not callable. You should access the items of your list with square brackets (i.e. spam[i] instead of spam(i)).

Also, when iterating on a list, you can avoid using range most of the time:

spam = ['apples' , 'bananas' , 'tofu' , 'cats']

for thing in spam:
    print(thing , end = ',')
Sign up to request clarification or add additional context in comments.

Comments

0

List slicing in python works like this spam[i], using normal brackets on something always means "calling" it, meaning treating it like a function to be called.

Comments

0

Your problem here is with this line:

print(spam(i) , end = ',')

In this instance, since you've encased i within rounded brackets, Python attempts to execute spam() as a Function while passing i as an argument. To fix this, use square brackets instead:

print(spam[i] , end = ',')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.