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 the 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
- 1 Create a list in Python
- 1.1 Using [ ] to create a list
- 1.2 List Creation – Examples
- 1.3 Python list – list() method to create a list
- 1.4 List Creation – Examples
- 1.5 Using list comprehension – An intuitive way to create lists
- 1.6 List Comprehension – Examples
- 1.7 Creating a multi-dimensional list
- 1.8 Extend a list using the extend() and append() methods
- 1.9 List Extend() Example
- 1.10 List Append() Example
- 2 Access a list in Python (Indexing the list)
- 3 Slicing a Python list
- 3.1 Slicing Examples
- 3.1.1 Return the three elements, i.e. [3, 4, 5] from the list
- 3.1.2 Print slice as [3, 5], Don’t change the first or last index
- 3.1.3 Slice from the third index to the second last element
- 3.1.4 Get the slice from start to the second index
- 3.1.5 Slice from the second index to the end
- 3.1.6 Reverse a Python list using the slice operator
- 3.1.7 Reverse a Python list but skipping the values at odd indices
- 3.1.8 Create a shallow copy of the full Python list
- 3.1.9 Get a copy of the list containing every other element
- 3.1 Slicing Examples
- 4 Iterate a list in Python
- 5 Add/Update elements to a list
- 6 Remove/Delete elements from a list
- 7 Searching elements in a list
- 8 Sorting a list in Python
- 9 Python list methods
- 10 Python list built-in 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.).
List Creation – Examples
# 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, ...]])
List Creation – Examples
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.
List Comprehension – Examples
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 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']
List Extend() Example
Alternately, you can join lists using the extend() method.
>>> L1 = ['a', 'b'] >>> L2 = ['c', 'd'] >>> L1.extend(L2) >>> print(L1) ['a', 'b', 'c', 'd']
List Append() Example
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.
Access a List using Index – Example
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 which returns the part of a sequence. It operates on objects of different data types such as strings, tuples, and works the same on a Python list.
It has a mystic syntax which is as follows.
#The Python slicing operator syntax [start(optional):stop(optional):step(optional)] Say size => Total no. of elements in the list. Start (x) -> It is the point (xth list index) where the slicing begins. (0 =< x < size, By default included in the slice output) Stop (y) -> It is the point (y-1 list index) where the slicing ends. (0 < y <= size, The element at the yth index doesn't appear in the slice output) Step (s) -> It is the counter by which the index gets incremented to return the next element. The default counter 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.
Print slice as [3, 5], Don’t change the first or last index
>>> theList[2:5:2] [3, 5]
In this example, we incremented the step counter by ‘2’ to exclude the median value, i.e., ‘4’ from the slice output.
Slice from the third index to the second last element
You can use a negative value for the stop argument. It means the traversing begins from the rearmost 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]
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.
Traversing a List – 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.
Modifying a List using Assignment Operator – Example
You can also refer the adding/extending the list section for updating the list.
Modifying a List using Insert Method – Example
You can also push one item at the target location by calling the insert() method.
theList = [55, 66] theList.insert(0,33) print(theList)
[33, 55, 66]
To insert multiple items, you can use the 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.
Delete List Elements using Del Operator
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)
Delete List Elements using Remove() and POP() methods
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 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.
Traversing a list in Python – Example
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 tried to cover one of the essential topics in Python. In whatever domain of Python, you choose to work, knowing lists is essentially help.