Adding Elements to a List in Python
A list in python is an ordered collection of items. It’s mutable and it can contain multiple data types including other lists. In this tutorial, we will cover how to create an empty list, add elements …
Updated
October 12, 2023
A list in python is an ordered collection of items. It’s mutable and it can contain multiple data types including other lists. In this tutorial, we will cover how to create an empty list, add elements to the list and also remove elements from the list.
- Creating an Empty List We can create an empty list in python using square brackets [] like so:
my_list = []
- Adding Elements to a List To add elements to a list, you use append method or extend method or the plus (+) operator for lists of single items. Here are examples of each:
- Append Method:
# initialize an empty list
my_list = []
# add element to the list using append method
my_list.append(1)
print(my_list) # Output: [1]
- Extend Method:
# initialize an empty list
my_list = []
# add multiple elements to the list using extend method
my_list.extend([2,3,4])
print(my_list) # Output: [1,2,3,4]
- Plus (+) Operator:
# initialize an empty list
my_list = []
# add multiple elements to the list using plus (+) operator
my_list += [5,6,7]
print(my_list) # Output: [1,2,3,4,5,6,7]
Remember that lists are mutable i.e., we can change their content after they have been created.
- Removing Elements from a List To remove elements from a list in python, you use the remove() method or the del keyword. Here are examples:
- Remove Method:
# initialize a list with elements
my_list = [1,2,3,4,5]
# remove an element using remove method
my_list.remove(2)
print(my_list) # Output: [1,3,4,5]
- Del Keyword:
# initialize a list with elements
my_list = [1,2,3,4,5]
# remove an element using del keyword
del my_list[1]
print(my_list) # Output: [1,3,4,5]
Note that when deleting items from a list, the index can change if not all elements are being removed.