Python Lists with examples
Introduction
This article provides a lot of information about Python lists. We will learn how to create lists, append and delete elements, sort lists and create slices.
List
List is a collection(array) which contains ordered elements. Each element of a list has its own index. Lists can be modified and therefore are called “mutable” objects. Lists also allow duplicate members.
Create a list
List is defined by specifying its elements inside the square brackets. It can contain a mixture of elements of different types, like strings, numbers and other objects:
list1 = ['word1', 'word2', 1, 1, 2, 3, 3, 4, 'another word']
To find the size(length) of the list we can use len() function:
>>> list1 = ['word1', 'word2', 1, 1, 2, 3, 3, 4, 'another word'] >>> print(len(list1)) 9
Our list contains 9 elements and each element has its own index. Let’s have a look at these indices.
List index
Python starts counting from zero when it comes to indexing, this means that the very first element of a list has index 0. The next element has index 1 and so on.
>>> list1 = ['word1', 'word2', 1, 1, 2, 3, 3, 4, 'another word'] >>> print(list1[0]) word1 >>> print(list1[1]) word2 >>> print(list1[8]) another word
We start counting from zero and go up until we reach the last element.
The good thing about Python lists is that we can also use negative indices which are sometimes more convenient that positive indices. The last element of the list has index -1, the second-to-last has index -2 and so on.
>>> print(list1[-1]) another word >>> print(list1[-2]) 4
Slices
We already know how to get a specific element from the list. Python also allows us to get a sublist (slice) of the list. The operation itself is called slicing and requires us to specify both the start index and the end index.
To extract the sublist, use list[index1:index2]. The resulting slice will include the elements starting from index1 and up to index2 (excluding index2 element itself). We can also use negative indices for slicing.
>>> list1 = ['word1', 'word2', 1, 1, 2, 3, 3, 4, 'another word'] >>> print(list1[1:3]) ['word2', 1] >>> print(list1[0:8]) ['word1', 'word2', 1, 1, 2, 3, 3, 4] >>> print(list1[-5:-1]) [2, 3, 3, 4]
We can also omit index1 or index2 when making a slice, for example the following slices are correct list[:3] or list[4:]. When we leave out index1 it means that the slicing will start from the very beginning of the list. When we leave out index2 it means that the slice will go till the end of the list.
Examples:
>>> list1 = ['word1', 'word2', 1, 1, 2, 3, 3, 4, 'another word'] >>> print(list1[:3]) ['word1', 'word2', 1] >>> print(list1[4:]) [2, 3, 3, 4, 'another word']
Append an element to a list
We can use append method to add a single element to the end of a list. That single element itself might also be a list. Look at the following examples:
>>> list1 = [1, 2, 3, 4] >>> list1.append(5) >>> print (list) [1, 2, 3, 4, 5] >>> list1.append([6, 7]) >>> print (list1) [1, 2, 3, 4, 5, [6, 7]]
First we append 5 to the end of our list. Next we try to append another list [6,7], and that list also gets appended as a single element.
How to append one list to another?
What if we want to concatenate(merge) two lists? We can use extend method for doing that:
>>> list1 = [1, 2, 3, 4] >>> list1.extend([5, 6]) >>> print(list1) [1, 2, 3, 4, 5, 6]
Now you see that two lists have been merged.
How to insert element in a list?
Method insert() allows us to insert any given element at a specific position in a list. When using insert method we should specify two arguments: the position(index) of a new element and the element itself.
>>> list1 = [1, 2, 3, 4] >>> list1.insert(3, 3.14) >>> print(list1) [1, 2, 3, 3.14, 4] >>> print(list1[3]) 3.14
How to remove the element from a list?
We can remove the element at a specific position from the list. The method pop() does exactly that and returns the removed element.
>>> list1 [1, 2, 3, 3.14, 4] >>> pi = list1.pop(3) >>> pi 3.14 >>> list1 [1, 2, 3, 4]
In the previous example we removed the element at index 3 and assigned the returned value(3.14) to the variable. When we call pop() method without specifying any argument the function returns and removes the last element of the list.
How to sort the list?
Python list objects have built-in method for sorting. Sort() method modifies the list itself. It can also perform reversed sort when called with argument “reverse” set to True:
>>> list1 = [5, 3, 1, 6, 10, 9] >>> list1.sort() >>> list1 [1, 3, 5, 6, 9, 10] >>> list1.sort(reverse=True) >>> list1 [10, 9, 6, 5, 3, 1]
If we do not want to modify the source list we can use the built-in function sorted() which returns the sorted list and doesn’t modify the initial list.
>>> list1 = [5, 3, 1, 6, 10, 9] >>> new_list = sorted(list1) >>> list1 [5, 3, 1, 6, 10, 9] >>> new_list [1, 3, 5, 6, 9, 10]
As you can see the initial list remains untouched while new_list contains the new sorted list.
The sorted() method comes in handy if you need to sort a tuple, because tuples are immutable (can’t be modified after creation) by definition, and therefore don’t support sort() method.
How to check whether an element is in a list?
We can use in operator, which returns a Boolean, to check if the element is in a list:
>>> list1 = [1, 2, 4] >>> 1 in list1 True >>> 3 in list1 False >>> 3 not in list1 True
How to find the smallest and the largest values in a list?
The built-in functions min() and max() will return the smallest and the largest values in a list, respectively:
>>> list1 = [1, 78, 3, 567] >>> min(list1) 1 >>> max(list1) 567 >>>
How to find an element in a list?
The index() method of a list returns the index of the element you are looking for:
>>> list1 = [1, 78, 3, 567] >>> list1.index(567) 3
Conclusion
In this article we have looked at the most common list operation examples in Python.
Hope this post was useful:)