In this class, you’ll learn what is Python list and how to use it in programs? It’ll also educate you about the various list operations such as slicing, searching, adding and removing elements.
A list in Python, also known as a sequence, is an ordered collection of objects. It can host object of any type: you can add numbers, letters, strings and even the nested lists as well.
Every element rests at some position (i.e., index) in the list. The index can be used later to locate a particular item. The first index begins at zero, next is one, and so forth.
Unlike strings, lists are mutable (or changeable) in Python. It implies that you can replace, add or remove elements.
Python List – Table of Content.
- Create a List in Python
- Access a List in Python (Indexing)
- Slicing Python Lists
- Iterate a List in Python
- Add/Update Elements in a List
- Remove/Delete Elements from a List
- Searching Elements in a List
- Sorting a List in Python
- Essential List Methods
- Built-in List Functions
Please note – you will need a Python IDE (such as IDLE or PyDev) as well as the Python Shell to test/run the sample code provided in the examples.
There are multiple ways to form a list in Python.
The first is by placing all the items (elements) inside a square bracket [ ], separated by commas.
L1 =  # empty list L2 = [expression, ...]
The list can take any number of elements, and each may belong to a different type (integer, float, string, etc.).
# blank list L1 =  # list of integers L2 = [10, 20, 30] # List of heterogenous data types L3 = [1, "Hello", 3.4]
Python includes a built-in list() method.
It accepts either a sequence or tuple as the argument and converts into a Python list.
Let’s start with an example to create a list without any element.
>>> theList = list() #empty list >>> len(theList) 0
Note- The len() function returns the size of the list.
You can supply a standard or nested sequence as the input argument to the list() function.
theList = list([n1, n2, ...] or [n1, n2, [x1, x2, ...]])
Try out the below Python list examples.
>>> theList = list([1,2]) >>> theList [1, 2]
>>> theList = list([1, 2, [1.1, 2.2]]) >>> theList [1, 2, [1.1, 2.2]] >>> len(theList) 3
Python supports a concept known as “List Comprehension.” It helps in constructing lists in a completely natural and easy way.
A list comprehension has the following syntax:
#Syntax - How to use List Comprehension theList = [expression(iter) for iter in oldList if filter(iter)]
It has square brackets grouping an expression followed by a for-in clause and zero or more if statements. The result will always be a list.
Let’s first see a simple example.
>>> theList = [iter for iter in range(5)] >>> print(theList)
[0, 1, 2, 3, 4]
Isn’t that was easy to start with a simple list.
Here is a more complicated example of List Comprehension resulting in a list creation.
>>> listofCountries = ["India","America","England","Germany","Brazil","Vietnam"] >>> firstLetters = [ country for country in listofCountries ] >>> print(firstLetters)
['I', 'A', 'E', 'G', 'B', 'V']
List comprehension even allows an if statement, to only add members to the list which are fulfilling a specific condition:
>>> print ([x+y for x in 'get' for y in 'set'])
['gs', 'ge', 'gt', 'es', 'ee', 'et', 'ts', 'te', 'tt']
Let’s now see how the if clause works with the list comprehension.
>>> print ([x+y for x in 'get' for y in 'set' if x != 't' and y != 'e' ])
['gs', 'gt', 'es', 'et']
Another complicated example is to create a list containing the odd months with List Comprehension syntax.
>>> months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] >>> oddMonths = [iter for index, iter in enumerate(months) if (index%2 == 0)] >>> oddMonths
['jan', 'mar', 'may', 'jul', 'sep', 'nov']
You can create a sequence with a pre-defined size, by specifying an initial value for each element.
>>> init_list = *3 >>> print(init_list) [0, 0, 0]
With the above concept, you can build a two-dimensional list.
two_dim_list = [ *3 ] *3
The above statement works but Python will only create the references as sublists instead of creating separate objects.
>>> two_dim_list = [ *3 ] *3 >>> print(two_dim_list) [[0, 0, 0], [0, 0, 0], [0, 0, 0]] >>> two_dim_list = 1 >>> print(two_dim_list) [[0, 0, 1], [0, 0, 1], [0, 0, 1]]
We changed the value of the third item in the first row, but the same column in other rows also got affected.
So, you must use list comprehensions to get around of the above issue.
>>> two_dim_list = [*3 for i in range(3)] >>> print(two_dim_list) [[0, 0, 0], [0, 0, 0], [0, 0, 0]] >>> two_dim_list = 1 >>> print(two_dim_list) [[0, 0, 1], [0, 0, 0], [0, 0, 0]]
Python allows lists to re-size in many ways. You can do that just by adding two or more of them.
>>> L1 = ['a', 'b'] >>> L2 = [1, 2] >>> L3 = ['Learn', 'Python'] >>> L1 + L2 + L3 ['a', 'b', 1, 2, 'Learn', 'Python']
Alternately, you can join lists using the extend() method.
>>> L1 = ['a', 'b'] >>> L2 = ['c', 'd'] >>> L1.extend(L2) >>> print(L1) ['a', 'b', 'c', 'd']
Next, you can append a value to a list by calling the append() method. See the below example.
>>> L1 = ['x', 'y'] >>> L1.append(['a', 'b']) >>> L1 ['x', 'y', ['a', 'b']]
You’ll find many ways of accessing or indexing the elements of a Python list.
The simplest one is to use the index operator ([ ]) to access an element from the list. Since the list has zero as the first index, so a list of size ten will have indices from 0 to 9.
Any attempt to access an item beyond this range would result in an IndexError. The index is always an integer. Using any other type of value will lead to TypeError.
Also, note that a Nested list will follow the nested indexing.
vowels = ['a','e','i','o','u'] consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'] #Accessing list elements using the index operator print(vowels) print(vowels) print(vowels) #Testing exception if the index is of float type try: vowels[1.0] except Exception as ex: print("Note:", ex) #Accessing elements from the nested list alphabets = [vowels, consonants] print(alphabets) print(alphabets)
a i u Note: list indices must be integers or slices, not float i d
Python enables reverse (or negative) indexing for the sequence data type. So, for Python list to index in the opposite order, you need to set the index using the minus (-) sign.
Indexing the list with “-1” will return the last element of the list, -2 the second last and so on.
vowels = ['a','e','i','o','u'] print(vowels[-1]) print(vowels[-3])
Python comes with a magical slice operator to carve objects of different data types such as strings, tuples. And it works the same on a Python list as well.
It has a mystic syntax which is as follows.
#The Python slicing operator syntax [start(optional):stop(optional):step(optional)] Start -> The starting index (By default included in the slice output) Stop -> The closing index (Excluded from the slice output) Step -> Tells how many values to exclude from the end. The default is 1.
Let’s consider the following list of integers.
>>> theList = [1, 2, 3, 4, 5, 6, 7, 8]
In the examples to follow, we’ll test various slice operations on this list.
Return the three elements, i.e. [3, 4, 5] from the list.
>>> theList[2:5] [3, 4, 5]
Since Python list follows the zero-based index rule, so the first index starts at 0.
Hence, you can see that we passed ‘2’ as starting index as it contains the value ‘3’ which is included in the slice by default.
And passing ‘5’ as the ending index meant to ensure the slice output can include elements up to the 4th index.
Get the slice containing [3, 4] without changing any of the starting or ending index.
>>> theList[2:5:2] [3, 5]
In this example, we incremented the step counter by ‘1’ to exclude the last two values from the slice output.
Slice from the third index to the second last element in the list.
You can use a negative value for the stop argument. It means the traversing begins from the last index.
A negative stop value such as ‘-1’ would mean the same as “length minus one.”
>>> theList[2:-1] [3, 4, 5, 6, 7]
Get the slice from start to the second index.
In slicing, if you leave the start, then it means to begin slicing from the 0th index.
>>> theList[:2] [1, 2]
Slice from the second index to the end.
While slicing a list, if the stop value is missing, then it indicates to perform slicing to the end of the list. It saves us from passing the length of the list as the ending index.
>>> theList[2:] [3, 4, 5, 6, 7, 8]
Reverse a Python list using the slice operator.
It is effortless to achieve this by using a special slice syntax (::-1). But please remember that reversing a list this way consumes more memory than an in-place reversal.
Here, it creates a shallow copy of the Python list which requires long enough space for holding the whole list.
>>> theList[::-1] [8, 7, 6, 5, 4, 3, 2, 1]
Here, you need a little pause and understand, why is the ‘-1’ after the second colon? It intends to increment the index every time by -1 and directs to traverse in the backward direction.
Reverse a Python list but skipping the values at odd indices.
Here, you can utilize the concept learned in the previous example.
>>> theList[::-2] [8, 6, 4, 2]
We can skip every second member by setting the iteration to ‘-2’.
Create a shallow copy of the full Python list.
>>> id(theList) 55530056 >>> id(theList[::]) 55463496
Since all the indices are optional, so we can leave them out. It’ll create a new copy of the list.
Get a copy of the list containing every other element.
>>> theList[::2] [1, 3, 5, 7]
Python provides a traditional for-in loop for iterating the list. The for statement makes it super easy to process the elements of a list one by one.
for element in theList: print(element)
If you wish to use both the index and the element, then call the enumerate() function.
for index, element in enumerate(theList): print(index, element)
If you only want the index, then call the range() and len() methods.
for index in range(len(theList)): print(index)
The list elements support the iterator protocol. To intentionally create an iterator, call the built-in iter function.
it = iter(theList) element = it.next() # fetch first value element = it.next() # fetch second value
Check out the below example.
theList = ['Python', 'C', 'C++', 'Java', 'CSharp'] for language in theList: print("I like", language)
I like Python I like C I like C++ I like Java I like CSharp
Unlike the string or tuple, Python list is a mutable object, so the values at each index can be modified.
You can use the assignment operator (=) to update an element or a range of items.
You can also refer the adding/extending the list section for updating the list.
Moreover, you can push one item at the target location by using the insert() method.
theList = [55, 66] theList.insert(0,33) print(theList)
[33, 55, 66]
To insert multiple items, you can use slice assignment.
theList = [55, 66] theList[2:2] = [77, 88] print(theList)
[55, 66, 77, 88]
You can make use of the ‘del’ keyword to remove one or more items from a list. Moreover, it is also possible to delete the entire list object.
vowels = ['a','e','i','o','u'] # remove one item del vowels # Result: ['a', 'e', 'o', 'u'] print(vowels) # remove multiple items del vowels[1:3] # Result: ['a', 'u'] print(vowels) # remove the entire list del vowels # NameError: List not defined print(vowels)
You can call remove() method to delete the given element or the pop() method to take out an item from the desired index.
The pop() method deletes and sends back the last item in the absence of the index value. That’s how you can define lists as stacks (i.e., FILO – First in, last out model).
vowels = ['a','e','i','o','u'] vowels.remove('a') # Result: ['e', 'i', 'o', 'u'] print(vowels) # Result: 'i' print(vowels.pop(1)) # Result: ['e', 'o', 'u'] print(vowels) # Result: 'u' print(vowels.pop()) # Result: ['e', 'o'] print(vowels) vowels.clear() # Result:  print(vowels)
Last but not the least, you can also remove items by assigning a blank list with a slice of its elements.
vowels = ['a','e','i','o','u'] vowels[2:3] =  print(vowels) vowels[2:5] =  print(vowels)
['a', 'e', 'o', 'u'] ['a', 'e']
You can use the Python ‘in’ operator to check if an item is present in the list.
if value in theList: print("list contains", value)
Using the Python list index() method, you can find out the position of the first matching item.
loc = theList.index(value)
The index method performs a linear search and breaks after locating the first matching item. If the search ends without a result, then it throws a ValueError exception.
try: loc = theList.index(value) except ValueError: loc = -1 # no match
If you would like to fetch the index for all matching items, then call index() in a loop by passing two arguments – the value and a starting index.
loc = -1 try: while 1: loc = theList.index(value, loc+1) print("match at", loc) except ValueError: pass
A better version of the above code is to wrap the search logic inside a function and call that function from a loop.
See the example below.
theList = ['a','e','i','o','u'] def matchall(theList, value, pos=0): loc = pos - 1 try: loc = theList.index(value, loc+1) yield loc except ValueError: pass value = 'i' for loc in matchall(theList, value): print("match at", loc+1, "position.")
match at 3 position.
Python list supports two methods min(List) and max(List). You can call them accordingly to find out the element carrying the minimum or the maximum value.
>>> theList = [1, 2, 33, 3, 4] >>> low = min(theList) >>> low 1 >>> high = max(theList) >>> high 33
Python list implements the sort() method for ordering (in both ascending and descending order) its elements in place.
Please note that in place sorting algorithms are more efficient as they don’t need temporary variables (such as a new list) to hold the result.
By default, the function sort() performs sorting in the ascending sequence.
theList = ['a','e','i','o','u'] theList.sort() print(theList)
['a', 'e', 'i', 'o', 'u']
If you wish to sort in descending order, then refer the below example.
theList = ['a','e','i','o','u'] theList.sort(reverse=True) print(theList)
['u', 'o', 'i', 'e', 'a']
You can use the built-in sorted() function to return a copy of the list with its elements ordered.
newList = sorted(theList)
By default, it also sorts in an ascending manner.
theList = ['a','e','i','o','u'] newList = sorted(theList) print("Original list:", theList, "Memory addr:", id(theList)) print("Copy of the list:", newList, "Memory addr:", id(newList))
Original list: ['a', 'e', 'i', 'o', 'u'] Memory addr: 55543176 Copy of the list: ['a', 'e', 'i', 'o', 'u'] Memory addr: 11259528
You can turn on the “reverse” flag to “True” for enabling the descending order.
theList = ['a','e','i','o','u'] newList = sorted(theList, reverse=True) print("Original list:", theList, "Memory addr:", id(theList)) print("Copy of the list:", newList, "Memory addr:", id(newList))
Original list: ['a', 'e', 'i', 'o', 'u'] Memory addr: 56195784 Copy of the list: ['u', 'o', 'i', 'e', 'a'] Memory addr: 7327368
Quick wrap up – Python List
In this tutorial, we hope to finish one of the most important topics in Python. In whatever domain of Python, you choose to work, knowing lists is essentially help.