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
Adiv Abramson
6,919 PointsNot so much a question but a comment on working with lists in Python.
I was just experimenting with lists and discovered a way of adding to besides using the append or extend methods. I'm sure this is painfully obvious to experienced Pythonistas but as a rank beginner I found it fascinating. Hope it's OK to post what may for most be obvious and trivial.
create a list
a = ['a', 'b', 'c']
add an element to the list
a + ['d'] #returns ['a', 'b', 'c', 'd'] ; didn't use append()
use augmented assignment operator to add another element
now let a be ['a', 'b', 'c', 'd']
a += ['e'] #a is now ['a', 'b', 'c', 'd', 'e']
add more than one element using augmented assignment
a += ['g', 'h'] #a is now ['a', 'b', 'c', 'd', 'e', 'g', 'h']; didn't use extend()
replicate/repeat list with * operator
a *=2 #a is now ['a', 'b', 'c', 'd', 'e', 'g', 'h', 'a', 'b', 'c', 'd', 'e', 'g', 'h']
I don't have any luck with -=. As far as I can tell, you have to use del or pop() to remove items from a list.
I thought it was pretty nifty to be able to manipulate lists in this manner. Hope this helps.
1 Answer
Adiv Abramson
6,919 PointsRight you are, boog690. I was being rather casual when writing this note. The values displayed are the results of the operations but list a remains unchanged unless an actual assignment is made. I will update my post so that it reflects your corrections. Thanks!
boog690
8,987 PointsNo worries. I just didn't want to confuse others that may try this and find variable a never contains 'd'.
Thanks again, Adiv!
boog690
8,987 Pointsboog690
8,987 PointsAwesome post! Thanks for that!
I'd like to point out that your second heading add an element to the list isn't exactly right. a + ['d'] would RETURN ['a', 'b', 'c', 'd'] but the variable a would still be ['a', 'b', 'c']. For example, if we ran something like:
we'd see variable a is still ['a', 'b', 'c'].
We would need an assignment to change the value of variable a:
a = a + ['d']would work.