NemanjaPython
NemanjaPython

Reputation: 13

AttributeError: 'int' object has no attribute 'append' simple problem with my list

MY CODE:

numbers = [1, 2, 3, 4, 5]
doubled_numbers = []

for num in numbers:
    doubled_numbers = num * 2
    doubled_numbers.append(doubled_numbers)

print(doubled_numbers)

I GOT:

Traceback (most recent call last):
  File "C:/Users/neman/Desktop/Junior Developer Vezbe/list comprehension.py", line 12, in <module>
    doubled_numbers.append([doubled_numbers])
AttributeError: 'int' object has no attribute 'append'

I have no idea why doesn't work, am I missing something or there is a typo? This is a simple thing but it bothers me very much

Upvotes: 0

Views: 2105

Answers (2)

Rabiul Islam
Rabiul Islam

Reputation: 56

you are overriding doubled_numbers in doubled_numbers = num * 2

change variable name like:

for num in numbers:
    doubled_number = num * 2
    doubled_numbers.append(doubled_number)

Upvotes: 1

Garam Lee
Garam Lee

Reputation: 137

doubled_numbers = num*2 overrides the list doubled_numbers into an integer (num*2).

To fix this you will have to change the name of the variable to something like new_number changing your code to:

numbers = [1, 2, 3, 4, 5]
doubled_numbers = []

for num in numbers:
    new_number = num * 2
    doubled_numbers.append(new_number)

print(doubled_numbers)

Also, you could remove a line of code and directly append the value of num*2 to your list:

doubled_numbers.append(num*2)

and then remove the line of code above it.

Upvotes: 1

Related Questions