Append list in Python
The append() method appends the values of another list to the end of the list.
The append() method is used to add elements to the end of an existing list.
The append() method accepts a list as an argument and appends it onto the end of your current list.
1. Using List.append()
To use the append() method, call it on a list object with one or more values. The following example appends a string to a list:
>>> my_list = [‘a’, ‘b’, ‘c’]
>>> my_list.append(‘d’)
>>> print(my_list)
[‘a’, ‘b’, ‘c’, ‘d’]
This example uses the append() method in conjunction with an integer index to add elements at particular locations in the original list:
>>> my_list2 = [‘a’] + [1]*3 + [‘b’]*3 + [4]*4 + [‘c’,’d’,’e’,’f’] # This is how we get our initial array ([[1], 2], 3, 4). Using this goes beyond what you would normally do with just one line of code, but hopefully you realize how powerful Python can be when used properly!
2. List Comprehension
List comprehension is a syntactic construct which allows us to build lists. List comprehension is a short way to create lists. List comprehension is used to create a new list from existing lists, for example:
“`python
from python_programming import *
# list comprehensions example 2
Note that the output from both list comprehensions and generator expressions are identical—the former just happens in an expression statement while the latter happens as part of function calls. It’s also important to note that there isn’t any difference between using square brackets or parentheses when defining generators; either will work just fine! Finally, it’s worth noting that if you ever want your generator expression or list comprehension to yield something other than an iterable object (like an integer), you can simply append its value directly onto the end of your expression:
3. Using extend() Method
The extend() method is used to append another list to a list.
The syntax of extend() method is as follows:
“`python
# appends one list with another
list1.extend(list2)
“`
This will add all items of ‘list2’ onto ‘list1’. The order of each item remains same. It’s just adding/appending values but not sorting them at all.
4. Using + operator
The + operator can be used to append elements of any type. This operation will return a list that contains the concatenated values. For example:
>>> lst1 = [1, 2]
>>> lst2 = [3, 4]
>>> lst3 = lst1 + lst2
>>> print(lst3)
[1, 2, 3, 4]
In this article, we have covered the four ways to append list in Python. We have also discussed some common mistakes that you can avoid while working with lists. If you are new to Python, then don’t hesitate to learn from our list of tutorials on the same topic.