In this tutorial we will learn about Python Lists using different examples and scenarios.
What is Python List?
- A list is a data structure in Python that is a mutable, ordered sequence of elements.
- Mutable means that you can change the items inside, while ordered sequence is in reference to index location.
- The first element in a list will always be located at index 0. Each element or value that is inside of a list is called an item.
- Just as strings are defined as characters between quotes, lists are defined by having different data types between square brackets
[ ]
. - Also, like strings, each item within a list is assigned an index, or location, for where that item is saved in memory.
- Lists are also known as a data collection. Data collections are simply data types that can store multiple items.
Comparison between different Python Data Types
Below table shows a summary of the differences between each data types:
Data Type | Ordered | Iterable | Unique | Immutable | Mutable |
---|---|---|---|---|---|
List | Yes | Yes | No | No | Yes |
Dictionary | No | Yes | Keys only | Keys only | Values only |
Tuple | Yes | Yes | No | Yes | No |
Set | No | Yes | Yes | No | Yes |
Frozenset | No | Yes | Yes | Yes | No |
Python list syntax
A list can be created by placing items inside square brackets and separated by comma character.
list([iterable])
Creating a list in python
Method-1: Create a list from tuple and string data type Using list()
We can assign different data type such as tuple, string with list()
to convert the data type into a list:
In this example I have defined a string and one tuple data type, then convert them into list using list()
and then we verify the data type using type()
function.
Output from this script:
~]# python3 create-list.py
my name in list format: ['d', 'e', 'e', 'p', 'a', 'k']
numbers in list format: [1, 2, 3, 4]
<class 'list'>
<class 'list'>
Method-2: Create a list using square brackets
This is the traditional method if you are defining a new list in your python code. You can place your list of items separated by comma character within square brackets. In this example I am creating different types of list enclosed within square brackets:
Output from this script:
~]# python3 create-list.py
<class 'list'>
<class 'list'>
<class 'list'>
So all three provided variables are python list in this example
Accessing elements within a list
In order to access a specific element within a list, you use an index. When we declare our list variable, each item is given an index. Remember that indexing in Python starts at zero and is used with brackets.
You can use both positive and negative index value to access the elements of a list
- A positive index value
0
will start the iteration from the first element, index 1 to access the second element and so on - A negative index value
-1
will represent the last element in the list, -2 to access the second last and so on
So in this example I have used both positive and negative index value to help you understand the usage and difference:
Output from this script:
~]# python3 access-list.py
First: 1
Second: 2
Last: 5
Second Last: 4
Declare a list with mixed data types
Lists can hold any data type, even other lists. Let’s check out an example of several data types:
Output from this script:
~]# python3 create-list.py
[2.5, 'string', True]
The script outputs 2.5 as the first item because when the list is defined, it stores the value of num
, not the variable itself.
Define and access lists within another list
We also have the flexibility to define a list inside another list. In this example I have defined a parent list cars
with some of the car manufacturers, in the second element of cars
I have created another list with some colors
. So I have created a list within another list:
Example-1: Access list with list using index
Let's try to access individual elements from both the lists, output from this script:
~]# python3 access-list.py
First: maruti
Second: ['blue', 'red']
Last: hyundai
Color: blue
To access items within a list normally, we simply use bracket notation and the index location. When that item is another list, you simply add a second set of brackets after the first set. Here the second index value returns the content of our child list ['blue', 'red']
and if we add one more index value then we can access the content of this child list as printed with Color
Example-2: Access string and integers inside list
Let's make this even more interesting, we were able to index the content of list within a list which makes sense. Similarly we can also index the individual characters of a string but the same can not be done for an integer.
let's check this example where I have now added an integer to my cars
list as the first element. Now using index value I will try to access the content of a string from fourth element i.e. hyundai and similarly I will try to access the content of integer using index value:
Output from the script:
~]# python3 access-list.py Fourth: hyundai Index fourth element: h First: 1234 Traceback (most recent call last): File "access-list.py", line 9, in print('Index first element: ', cars[0][1]) ## this will fail TypeError: 'int' object is not subscriptable
So indexing a string was successful but while trying to index the integer we get TypeError
.
To get a little bit more understanding of how multi-indexing works, check out below Table
Index location | Value at location | Data Type | Can be Indexed again |
---|---|---|---|
0 | 1234 | Integer | No |
1 | honda | String | Yes |
2 | ['blue', 'red'] | List | Yes |
NA | True or False | Boolean | No |
Iterate over list items using for loop
Since we know that Python list data type is iterable, we can use for loop to iterate over individual elements of the list:
Output from this script:
~]# python3 list-for-loop.py
apple
mango
guava
grapes
Add elements to python list
There are different methods list.append(item)
, list.extend(iterable)
, list.insert(index, item)
to add elements to an existing python list, let's explore each one of them individually:
Method-1: Append item to existing list using list.append(item)
We will use list.append(item)
to add a single item to the end of a list. This doesn't return a new list instead it only modifies the original list.
#!/usr/bin/env python3 num = [1, 2, 3, 4] num.append(5) print(num)
In this example we are appending 5 to our existing list which contains numbers from 1 to 4, output from this script:
~]# python3 list-append.py
[1, 2, 3, 4, 5]
If I try to append more than one item using num.append(5, 6)
then I get TypeError
as only one element can be added at a time.
~]# python3 list-append.py
Traceback (most recent call last):
File "list-append.py", line 5, in
num.append(5, 6)
TypeError: append() takes exactly one argument (2 given)
Method-2: Add element to a list using list.extend(iterable)
The list.extend(iterable)
method takes one argument, which should be an iterable data type. It then extends the list by appending all of the items from the iterable to the list.
We can take the existing example where wo got the TypeError
, now I will add 5 and 6 into our existing list using extend(iterable)
#!/usr/bin/env python3 num = [1, 2, 3, 4] num.extend([5, 6]) ## Append in the list format print(num)
Here notice that I am adding 5 and 6 in list format num.extend([5, 6])
, so the output would be success:
~]# python3 list-extend.py
[1, 2, 3, 4, 5, 6]
We can also create another list and extend the existing one:
#!/usr/bin/env python3 num = [1, 2, 3, 4] extra = [5, 6] num.extend(extra) print(num)
This will also give us the same result:
~]# python3 list-extend.py
[1, 2, 3, 4, 5, 6]
We can also add string using extend(iterable)
but a string would be broken into individual character and each char will act as single element, for example:
#!/usr/bin/env python3 num = [1, 2, 3, 4] num.extend('string') print(num)
Output from this script:
~]# python3 list-extend.py
[1, 2, 3, 4, 's', 't', 'r', 'i', 'n', 'g']
So each character of the string is added as an element into the list.
Method-3: Add item at a certain position in a list
The list.insert(index, item)
method (as the name suggests) inserts an item at a given position in a list. The method takes two arguments, index and item. The index is the position in the list before which to insert the item defined in the second argument. Both arguments are required.
In this example we are inserting 'three' at index position 2 i.e. the third element:
#!/usr/bin/env python3 num = ['one', 'two', 'four', 'five'] num.insert(2, 'three') print(num)
Output from this script:
~]# python3 list-append.py
['one', 'two', 'three', 'four', 'five']
Remove item from a list
We can use list.remove(item)
, list.pop([index])
to remove an element from a list or list.clear()
to remove all the elements from the list. Let's explore each method individually:
Method-1: Remove single item the list with list.remove(item)
The list.remove(item)
method removes from the list the first item whose value matches the argument item that's passed in. In this python code I have duplicate elements 'one' at first and third index position, let me try to remove 'one' using list.remove(item)
#!/usr/bin/env python3 num = ['one', 'two', 'four', 'five'] num.remove('one') print(num)
Output from this script:
~]# python3 list-append.py
['two', 'one', 'five']
As you see, only the first match for provided element 'one
' was removed while the third element with the same value was left intact.
Method-2: Remove item from the list using index position with list.pop([index])
The list.pop([index])
method removes the item at the given index of the list, and returns it. In this example I am removing an element based on it's index value and storing it into a different variable:
Output from this script:
~]# python3 list-append.py
my list: ['one', 'three', 'four']
removed item: two
The index is an optional argument, and if it isn't passed in, the method will remove the last item in the list. In this example I am not giving any index value which will remove the last element from the list:
Output from this script:
~]# python3 list-append.py
my list: ['one', 'two', 'three']
removed item: four
Get index position of an element within a specified range list.index(item [, start [, end]])
The list.index(item [, start [, end]])
method returns the index of the first item in the list whose value is item.
The parameters start and end are optional, and they indicate the position in the list at which the search for said item should start and end, respectively. Again, the very beginning of the list is index zero. The index at the end of the list is one less than the length of the list.
In this example I have covered different scenarios wherein the first two print statement will search the entire list for the provided element while the third and fourth print statement contains a specific range under which the provided element must be searched.
Output from this script:
~]# python3 index-position.py Index position of apple: 1 Index position of guava: 2 Traceback (most recent call last): File "index-position.py", line 7, in print('Index position of guava: ', fruits.index('grapes', 0, 3)) ValueError: 'grapes' is not in list
As expected the fourth print statement has failed as there we had specified a index range from 0 to 3 to search for guava while guava is in 4th index position in which case we will get ValueError
.
Count the items in the list using list.count(item)
The list.count(item)
method returns the number of times the given item occurs in the list. In this example we will count the occurrences of an element within the provided list:
Output from this script:
~]# python3 count-elements.py
count of mango in the list: 2
count of apple in the list: 1
Reverse the order of elements in list using list.reverse()
The reverse()
method enables the reversing the order of the list elements as shown in the following example:
#!/usr/bin/env python3 num = [1, 2, 3, 4] num.reverse() ## reverse the element order in the list print(num) ## print the new content of the list
Output from this script:
~]# python3 reverse-list.py
[5, 4, 3, 2, 1]
Sorting the elements of a list using list.sort()
Lists have only one special method: list.sort(*, key=None, reverse=False)
. By default, sort()
performs an A-Z-style sort, with lower values on the left. Using key allows the use of an additional function to modify the default sort, while reverse performs a Z-A sort.
Example-1: Default sorting
In this example we will just use sort()
function to sort the integers within a list
#!/usr/bin/env python3 num = [4, 3, 1, 2, 5, 7] num.sort() ## sort the order of the provided list print(num) ## print the new content of the list
Output from this script:
~]# python3 sort-list.py
[1, 2, 3, 4, 5, 7]
Example-2: Sort a list with key using list.sort(*, key=None, reverse=False)
The list.sort(*, key=None, reverse=False)
returns a new sorted list from the items in iterable.
- key specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example,
key=str.lower
). The default value isNone
(compare the elements directly). - reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
In this example we have provided the key type which should be used to perform the sorting. Additionally we can also specify the reverse value, in my case I have left it to False
#!/usr/bin/env python3 num = [4, 3, 1, 2, 5, 7] num.sort(key=int, reverse=False) ## sort the integers print(num) week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday'] week.sort(key=str, reverse=False) ## sort the strings print(week)
Output from this script:
~]# python3 sort-list.py
[1, 2, 3, 4, 5, 7]
['Monday', 'Thursday', 'Tuesday', 'Wednesday']
When a list consists of a collection of strings, they are sorted in the alphabetical order.
Copy elements from one list to another list using list.copy()
The list.copy()
method returns a shallow copy of a list. In this example I am copying the content of num
into a new list num_copied
Output from this script:
~]# python3 list-copy.py
Original List: [4, 3, 1, 2, 5, 7]
Copied List: [4, 3, 1, 2, 5, 7]
Original modified list: [5, 3, 1, 2, 5, 7]
Copied List: [4, 3, 1, 2, 5, 7]
As you see even if I update the content of original list, it has no impact on the newly created copied list. So both are not linked to each other.
Conclusion
In this tutorial we learned about Python list data type in detail with different examples and scenarios. We have looked at the various methods that are available for lists, and how to use them in practical applications. We have also seen how we can use list comprehensions to make the task of building lists programmatically easier.