Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Why am i not able to reduce the list by using -= where as I was able to add to the list using +=

Similar to the way of adding new items to the list using += why does not python allow me to remove the items from a list using -=

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points

The += syntax works because adding an item or another list to a list works.

Trying to use the in-place subtract -= doesn't have a meaning when used with lists since subtracting one list from another is not allowed. Trying to do so will raise a TypeError:

TypeError: unsupported operand type(s) for -: 'list' and 'list'

More on operators is in the docs.

Nathan Tallack
Nathan Tallack
22,164 Points

Now be patient with me on this one. I am just as new to this as you. :)

I know that a list is a builtin type for python. And as most types do, it has it's own methods for manipulating its objects.

Consider the python docs for the methods that this type has.

Now, I am not sure about using the += and -= operators on a list type. But one thing I am sure of with Object Orientated Programming is making use of the methods that your object comes for manipulating data within object.

Now I believe the + operator for lists overloads on the extend() method. I think. May be wrong on this. But the outcomes do look the same. If I was a little smarter with python I could look at the class definition for list type and understand it, but that is a little beyond me right now.

So consider what you are trying to do, and determine if one of those methods listed would be suitable for your requirements. :)