In this tutorial, we will learn everything about Python list, how to create a list, how to add or remove data from it, and all possible manipulations. So let’s get started.
What is a Python list?
A list in python is a sequence of comma-separated values enclosed with square brackets []. A single list can contain different types of data types such as strings, integers, numbers or any other valid data types.
Note: Lists are mutable i.e. they can be changed after creation.
How to create a Python list?
In Python, a list can be created by just placing all the list items inside square brackets [] and separating each list item by a comma.
# Create an empty list empty_list = [] # A list of integer values int_list = [1, 2, 3, 4] # A list of names name_list = ['John', 'Smith', 'Sophia'] # A list of mixed data types mixed_list = [1, 'Programmers', 2, 'Portal', 3.14]
Accessing list items
Now that we have learned how to create a list, it’s time to access the list items. List items can be accessed using list indexes. In Python, the list index starts from 0.
Suppose we have a Python list containing 5 list items as shown in the image below. The first item has an index of 0, the second item 2, the third item 3 and so on.
# A program to demonstrate indexing in a Python list. sample_list = ['Welcome', 'to', 'Programmers', 'Portal'] print(sample_list[0]) # Output: Welcome print(sample_list[1]) # Output: to print(sample_list[2]) # Output: Programmers print(sample_list[3]) # Output: Portal
Output:
Welcome
to
Programmers
Portal
Accessing list items using negative indexing
It is also possible to use a negative index to access a list item. A negative index starts from the end of the list. The last item has an index as -1, the second last as -2, the third last item as -3 and so on until the beginning of the list. In negative indexing, we basically traverse a python list in the reverse direction.
Note: Index -1 always refers to the last item in the list.
# Program to demonstrate Negative Indexing sample_list = ['Portal', 'Programmers', 'to', 'Welcome'] print(sample_list[-1]) # Output: Welcome print(sample_list[-3]) # Output: Programmers print(sample_list[-4]) # Output: Portal
Output:
Welcome
Programmers
Portal
How to get the size of a list?
We can use the built-in method len() to get the size of a list.
Note: len() method can be used to get the size of a string, tuple, dictionary, etc.
# Program to demonstrate list size empty_list = [] print(len(empty_list)) sample_list = [1, 2, 3, 4] print(len(sample_list))
Output:
0
4
Splitting(slicing) a Python list
List splitting or slicing is a very powerful concept provided by Python. It is used to break a list into smaller lists, at any desired position. Let’s understand it by an example.
# A program to demonstrate list splitting or slicing # sample_list[start:end] # Includes start index # Excludes end index sample_list = [1, 2, 3, 4, 5, 6, 7] # Print a list staring from index 1 upto index 4(Excludes index 5) print(sample_list[1:5]) # Print a list starting from index 0 upto index 2(Excludes index 3) print(sample_list[0:3]) # Print a list starting from index 2 upto end of the list print(sample_list[2:]) # Print a list start from index 0 upto index 4 print(sample_list[:5]) # print whole list print(sample_list[:]) # Negative indexing is also possible in slicing # Print list from index -5 to index -1 print(sample_list[-5:-1]) # Rest possible cases in negative indexing you can try yourself.
Output:
[2, 3, 4, 5]
[1, 2, 3]
[3, 4, 5, 6, 7]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7]
[3, 4, 5, 6]
Add elements to a list
As we already know, lists are mutable, meaning a list can be changed after it’s creation. So we can add new items to it.
There are three inbuilt methods which can be used to add new items to a list.
- Using append() method
- Using extend() method
- Using insert() method
1. Using append() method
This method can only add a single item at a time to the end of the list.
# Program to explain append() method sample_list = [] # Creates an empty list print(sample_list) sample_list.append(1) print(sample_list) sample_list.append(2) print(sample_list) sample_list.append('Programmers Portal') print(sample_list)
Output:
[]
[1]
[1, 2]
[1, 2, Programmers Portal]
2. Using extend() method
As we just learned, append() method can only add a single item at a time. What if we want to add multiple items at a time. That’s what extend() method does. It adds multiple items to the list at a time.
# Program to explain extend() method sample_list = [1, 2, 3, 4] print('List before: ', sample_list) sample_list.extend([5, 6, 7]) print('List after adding elements: ', sample_list) # You can use also pass a second list as a variable in extend() method first_list = [1, 2, 'Welcome', 'to'] second_list = ['Programmers', 'Portal'] # List before adding elements print('List before: ', sample_list) # List after adding elements first_list.extend(second_list) print('List After: ', first_list)
3. Using insert() method
append() and extend() both methods add items only to the end of the list. But what if we want to add element at any given position. insert() method helps us to do so. It can add a list item at any specified position.
insert(position, item)
insert() method takes two parameters. First is the position parameter, which specifies the position of the item where it will be added to the list. The second parameter is the value of the item to be added. A list item can be of any valid(or a user-defined) data type.
sample_list = [1,2,3,4,5] #Add an item to the beginning of the list sample_list.insert(0, 'Programmers') print(sample_list) # Add an item at index 3 sample_list.insert(3,'Portal') print(sample_list) # Add an item at the end of the list sample_list.insert(7, 'Last item') print(sample_list)
Output:
['Programmers', 1, 2, 3, 4, 5]
['Programmers', 1, 2, 'Portal', 3, 4, 5]
['Programmers', 1, 2, 'Portal', 3, 4, 5, 'Last item']
Updating items in a Python list
As we already know that Python lists are mutable. Therefore we can modify its items. List indexes are used to update any existing item. Let’s understand it by an example.
# Updating a Python list sample_list = [1, 2, 3, 4, 5, 6, 7, 8] print('Initial List: ', sample_list) # Replace item 3 with 'Programmers' sample_list[2] = 'Programmers' print(sample_list) # Replace item 5 with 'Portal' sample_list[4] = 'Portal' print(sample_list)
Output:
Initial List: [1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 'Programmers', 4, 5, 6, 7, 8]
[1, 2, 'Programmers', 4, 'Portal', 6, 7, 8]
Remove/Delete list items
Python provides four different built-in methods which can be used to remove items from a list. These four methods are as below
- remove() method
- del keyword
- pop() method
- clear() method
Let’s discuss each method one by one.
1. Using remove() method
remove() method removes a list item by value. It takes a parameter, which is the value of the item to be removed from the list. It does not return any value after removing a specified item.
remove(item)
# Program to explain remove() method in a Python list sample_list = [1, 2, 3, 4, 5, 'Programmers', 'Portal', 'Welcome', 10] print('Initial List: ',sample_list) # Remove first item sample_list.remove(1) print('After removing first item: ',sample_list) # Remove 'Welcome' from list sample_list.remove('Welcome') print("After removing 'Welcome': ", sample_list)
Output:
Initial List: [1, 2, 3, 4, 5, 'Programmers', 'Portal', 'Welcome', 10]
After removing first item: [2, 3, 4, 5, 'Programmers', 'Portal', 'Welcome', 10]
After removing 'Welcome': [2, 3, 4, 5, 'Programmers', 'Portal', 10]
2. Using the del keyword
The del keyword has an advantage over the remove() method as it can be used to delete the whole list at a time. del keyword also removes an item by value.
# Remove list items using del keyword sample_list = [1, 2, 3, 4, 5] print(sample_list) # Delete item 4 del sample_list[3] print('After deleting 4: ', sample_list) # Delete first item del sample_list[0] print('After deleting first item: ', sample_list) # Delete the whole list del sample_list print('After deleting list itself: ', sample_list) # Note: This line will throw an error as list is already deleted completely
Output:
[1, 2, 3, 4, 5]
After deleting 4: [1, 2, 3, 5]
After deleting first item: [2, 3, 5]
Traceback (most recent call last):
File "jdoodle.py", line 15, in <module>
print('After deleting list iteself: ', sample_list) # Note: This line will throw error as list is already deleted completely
NameError: name 'sample_list' is not defined
3. Using pop() method
The pop() method is generally used to remove the last item from the list. However, it can take a parameter as an index of the item to be removed and can remove a list item from any specified position.
The parameter is optional. If you specify, It removes the item from the specified position. Otherwise, it removes the last item.
Note: pop() method returns the value of the item to be removed.
# Program to demonstrate pop() method sample_list = [1, 2, 3, 4, 5] print('Initital List: ', sample_list) # Remove the last element removed_item = sample_list.pop() print('After removing last item: ', sample_list) print('Removed item', removed_item) # Remove item 3 from the list removed_item = sample_list.pop(2) # Pass index of item 3 as parameter, which is 2 print('After removing item 3: ', sample_list) print('Removed item: ', removed_item)
Output:
Initital List: [1, 2, 3, 4, 5]
After removing last item: [1, 2, 3, 4]
Removed item 5
After removing item 3: [1, 2, 4]
Removed item: 3
4. Using clear() method
The clear() method removes all the list items from a Python list. But it does not delete it permanently as the del keyword does. It does not take any parameter and also does not return any value.
# Program to explain clear() method in a Python list sample_list = [1, 2, 3, 4, 5] print('Initial List: ', sample_list) # Remove all list items sample_list.clear() print('After removing list items: ',sample_list) # Print an empty [] list.
Output:
Initial List: [1, 2, 3, 4, 5]
After removing list items: []