In this class, you’ll learn what is 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.

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.

Python List - A Beginners Guide to Get Started Quickly  - Python List A Beginners Guide to Get Started Quickly - Python List – A Beginners Tutorial to Get Started Quickly

Python List – A Guide

Create a list in Python

There are multiple ways to form a list in Python.

Using [ ] to create a list

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 list – list() method to create a list

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)

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)

Using list comprehension – An intuitive way to create lists

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[0] 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']

Creating a multi-dimensional list

You can create a sequence with a pre-defined size, by specifying an initial value for each element.

>>> init_list = [0]*3
>>> print(init_list)
[0, 0, 0]

With the above concept, you can build a two-dimensional list.

two_dim_list = [ [0]*3 ] *3

The above statement works but Python will only create the references as sublists instead of creating separate objects.

>>> two_dim_list = [ [0]*3 ] *3
>>> print(two_dim_list)
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> two_dim_list[0][2] = 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 = [[0]*3 for i in range(3)]

>>> print(two_dim_list)

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

>>> two_dim_list[0][2] = 1

>>> print(two_dim_list)

[[0, 0, 1], [0, 0, 0], [0, 0, 0]]

List extension

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']]

Access a list in Python (Indexing the list)

You’ll find many ways of accessing or indexing the elements of a Python list.

Using the index operator

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

#Testing exception if the index is of float type
except Exception as ex:
 print("Note:", ex)

#Accessing elements from the nested list
alphabets = [vowels, consonants]


Output –

Note: list indices must be integers or slices, not float

Reverse indexing

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']



Output – 


Slicing a Python list

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 -> 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)
>>> id(theList[::])

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]

Iterate a list in Python

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:

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)):

The list elements support the iterator protocol. To intentionally create an iterator, call the built-in iter function.

it = iter(theList)
element = # fetch first value
element = # fetch second value

Check out the below example.

theList = ['Python', 'C', 'C++', 'Java', 'CSharp']

for language in theList:
 print("I like", language)

Output –

I like Python
I like C
I like C++
I like Java
I like CSharp

Add/Update elements to a list

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.

theList = ['Python', 'C', 'C++', 'Java', 'CSharp']

theList[4] = 'Angular'

theList[1:4] = ['Ruby', 'TypeScript', 'JavaScript'] 

Output –

['Python', 'C', 'C++', 'Java', 'Angular']
['Python', 'Ruby', 'TypeScript', 'JavaScript', 'Angular']

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]



Output –

[33, 55, 66]

To insert multiple items, you can use slice assignment.

theList = [55, 66]

theList[2:2] = [77, 88]


Output –

[55, 66, 77, 88]

Remove/Delete elements from a list

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[2]

# Result: ['a', 'e', 'o', 'u'] 

# remove multiple items
del vowels[1:3]

# Result: ['a', 'u']

# remove the entire list
del vowels

# NameError: List not defined

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']


# Result: ['e', 'i', 'o', 'u']

# Result: 'i'

# Result: ['e', 'o', 'u']

# Result: 'u'

# Result: ['e', 'o']


# Result: []

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] = []

vowels[2:5] = []


['a', 'e', 'o', 'u']
['a', 'e']

Searching elements in a list

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.

    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
    while 1:
        loc = theList.index(value, loc+1)
        print("match at", loc)
except ValueError:

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
        loc = theList.index(value, loc+1)
        yield loc
    except ValueError:

value = 'i'
for loc in matchall(theList, value):
    print("match at", loc+1, "position.")

Output –

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
>>> high = max(theList)
>>> high

Sorting a list in Python

List’s sort() method

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']
['a', 'e', 'i', 'o', 'u']

If you wish to sort in descending order, then refer the below example.

theList = ['a','e','i','o','u']
['u', 'o', 'i', 'e', 'a']

Built-in sorted() function

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

Python list methods


It adds a new element to end of the list.


It extends a list by adding elements from another list.


It injects a new element at the desired index.


It deletes the desired element from the list.


It removes as well as returns an item from the given position.


It flushes out all elements of a list.


It returns the index of an element that matches first.


It returns the total no. of elements passed as an argument.


It orders the elements of a list in an ascending manner.


It inverts the order of the elements in a list.


It performs a shallow copy of the list and returns.

Python list built-in functions


It returns True if the list has elements with a True value or is blank.


If any of the members has a True value, then it also returns True.


It returns a tuple with an index and value of all the list elements.


The return value is the size of the list.


It converts all iterable objects and returns as a list.


The member which has the maximum value.


The member which has the minimum value.


It returns the sorted copy of the list.


The return value is the aggregate of all elements of a list.

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.

Anyways, if you find something new to learn today, then do share it with others. And, follow us on our social media (Facebook/Twitter) accounts to see more of this.



Source link


Please enter your comment!
Please enter your name here