0

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

1
  • 2
    doubled_numbers = num * 2 will over-write with int value, instead do doubled_numbers.append(num * 2) & remove line above that Commented Aug 20, 2020 at 11:02

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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)

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.