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
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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.