In Python, lists are a common data structure that holds multiple elements. In this post, learn how you use Python to append to a list.
Appending to a List with Append()
Let's say you've got a list (or array for you non-Pythonistas) with a set number of string elements represented by colors.
>>> colors = ['blue','red','green']
To append an element in Python to append to a list, we can use the
append() method. This method pushes a list element onto the end.
For example, perhaps we need to add the color black to the
colors list we just created. To do that, we'd call the
append() method and pass the string
black as the argument.
colors list should now have the
black element appended to it. To verify, simple reference the
colors list. Below, you can see that
black has been appended to the list.
>>> colors ['blue', 'red', 'green', 'black']
Appending to a List with Extend()
Alternatively, you can also use the
extend() (docs.python.org) list method to append to a list. Although this time, you're not appending a single element but another list.
Perhaps you need to add multiple colors to our
>>> colorsToAdd = ['yellow','pink'] >>> colors.extend(colorsToAdd) >>> colors ['blue', 'red', 'green', 'black', 'yellow', 'pink']
extend() method merges two lists together and appends another list to the end of the original.
Join the Jar Tippers on Patreon
It takes a lot of time to write detailed blog posts like this one. In a single-income family, this blog is one way I depend on to keep the lights on. I'd be eternally grateful if you could become a Patreon patron today!Become a Patron!
Subscribe to Adam the Automator
Get the latest posts delivered right to your inbox