List Comprehensions in Python
A list is one of the fundamental data types in Python. Every time you come across a variable name that’s followed by a square bracket []
, or a list
constructor, it is a list capable of containing multiple items, making it a compound data type. Similarly, it is also a breeze to declare a new list and subsequently add one or more items to it.
Let us create a new populated list, for example:
>>> new_list = [1, 2, 3, 4, 5]
>>> new_list
[1, 2, 3, 4, 5]
Or we can simply use the append()
method to add anything you want to the list:
>>> new_list.append(6)
>>> new_list
[1, 2, 3, 4, 5, 6]
If you need to append multiple items to the same list, the extend()
method will come in handy. You simply need to pass the list of items to append to the extend
method, as shown below:
>>> new_list.extend([7, 8, 9])
>>> new_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
As you can see, creating a list and appending it with other items is just a piece of cake. You can accomplish this task without having to