Python List



Python List

The list is the most versatile datatype available in Python that can be written as a list of comma-separated items.

The list is used to store multiple items in a single variable.

The list is one of 4 built-in data types in Python used to store collections of data. The other 3 are Set, Tuple, and Dictionary.

A List can be created using square brackets.


How to create a list?

You can create a list in Python by placing all items inside square brackets [], separated by commas.

A list can have any number of items that can be from different types (integer, float, string, etc.).

# empty list
my_list = []

# list of strings
fruits = ["kiwi", "apple", "blueberry", "dragonfruit"]

# list with mixed data types
my_mixed_list = ["hello", 10, 23.6]

# a list inside another
my_list = ["hello", ["a", "b", "c"], [7, 8, 9]]

List Items

A List is a collection of items that are ordered, changeable, and allow duplicate items.


Ordered

In Python, a list is ordered. It means that the items inside the list have a defined order, and the order will not change.

When you add a new item to a list, it will be placed at the end of the list.


Changeable

In Python, a list is changeable. It means that you can change, add, or remove items in a list after its creation.


Allow Duplicates

Since a list is indexed, it can allow duplicate items.

fruits = ["kiwi", "apple", "blueberry", "dragonfruit", "apple"]
print(fruits)

Output:

['kiwi', 'apple', 'blueberry', 'dragonfruit', 'apple']

List Length

You can use the len() function to determine how many items a list has.

fruits = ["kiwi", "apple", "blueberry", "dragonfruit"]
print(len(fruits))

Output:

4

List Items - Data Types

In Python, list items can be of any data type.

my_list1 = ["kiwi", "apple", "blueberry"]
my_list2 = [True, False, True]
my_list3 = [7, 31, 24, 9, 75]

print(my_list1)
print(my_list2)
print(my_list3)

Output:

['kiwi', 'apple', 'blueberry']
[True, False, True]
[7, 31, 24, 9, 75]

A list can have different data types.

my_list = ["kiwi", "apple", "blueberry"]

type()

In Python, a list is defined as objects with the data type 'list'.

my_list = ["kiwi", "apple", "blueberry"]
print(type(my_list))

Output:

<class 'list'>

The list() Constructor

You can also use the list() constructor to create a new list.

my_list = list(("kiwi", "apple", "blueberry"))
print(type(my_list))
print(my_list)

Output:

<class 'list'>
['kiwi', 'apple', 'blueberry']

Access List Items

There are different ways that you can use to access the items of a list.


List Index

List items are indexed and to access them, you can use the index operator [].

In Python, indices start at 0. For example, a list having 7 items will have an index from 0 to 6.

If you try to access indexes other than the allowed interval, an IndexError exception will be raised.

The index of a list must be an integer. You can't use float or other types. This will raise a TypeError exception.

my_list = ['apple', 'blueberry', 'kiwi', 'orange', 'watermelon', 'mango']

# Output: apple
print(my_list[0])

# Output: orange
print(my_list[3])

# Output: mango 
print(my_list[5])

# Error. Only integer can be used for indexing
print(my_list[3.0])

Output:

apple
orange
mango

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

To access nested lists, you can use nested indexing.

# Nested list
my_list = ["hello", [6, 16, 7, 9, 32]]

print(my_list[0][3])

print(my_list[1][4])

Output:

l 
32

Negative Indexing

Python allows negative indexing for its sequences.

The index of -1 refers to the last item, -2 refers to the second-last item, and so on.

Let us see the following example:

my_list = ['p', 'y', 't', 'h', 'o', 'n']

print(my_list[-1])

print(my_list[-5])

After executing the above code, the output will be as follows:

n
y

The following illustration shows the index and the negative index of a list:

List indexing in Python

How to slice a list in Python?

You can specify a range of indexes by indicating where a range starts and ends using the slicing operator : (colon).

The return value of a specified range will be a new list with the designated items.

Let us see the following examples:

fruits = ["kiwi", "apple", "blueberry", "dragonfruit", "banana", "peach", "mango", "grapes"]

# items 4th to 5th
print(fruits[3:5])

# items 5th to end
print(fruits[4:])

# items beginning to end
print(fruits[:])

After executing the above code, the output will be as follows:

['dragonfruit', 'banana']
['apple', 'peach', 'mango', 'grapes']
['kiwi', 'apple', 'blueberry', 'dragonfruit', 'banana', 'peach', 'mango', 'grapes']

Note: Remember when using the range of index that the start is included but not the end.


Slicing using a Range of Negative Indexes

You can use negative indexes if you want to start the search from the end of the list.

The following example returns the items from "dragonfruit" (-5 index) to "mango" (-2 index) but without including the last one.

fruits = ["kiwi", "apple", "blueberry", "dragonfruit", "banana", "peach", "mango", "grapes"]

print(fruits[-5:-2])

Output:

['dragonfruit', 'banana', 'peach']

Check if Item Exists in a list

You can check if an item is present in a list using the in keyword.

In the following example, we will check if "blueberry" is present in the "fruits" list.

fruits = ["kiwi", "apple", "blueberry", "dragonfruit", "banana", "peach", "mango", "grapes"]

if "blueberry" in fruits:
    print("Yes, 'blueberry' is on the list of the fruits")

Output:

Yes, 'blueberry' is on the list of the fruits

Change List Items

In Python, there are different ways that you can use to change list item values.


Change Item Value

To change the value of a specific item, you can specify the index number of that item.

In the following example, we will change the 3rd item of the fruit list.

fruits = ["kiwi", "apple", "blueberry", "dragonfruit", "banana"]

fruits[2] = "peach"

print(fruits)

Output:

['kiwi', 'apple', 'peach', 'dragonfruit', 'banana']

Change a Range of Item Values

Python offers the possibility to change the value of items within a specific range. You can define a list with the new values and refer to the range index numbers where you want to replace the old value with the new values.

In the following example, we will change the values "apple" and "peach" with the values "pineapple" and "avocado".

fruits = ["kiwi", "apple", "blueberry", "dragonfruit", "banana", "peach", "mango", "grapes"]

fruits[4:6] = ["pineapple", "avocado"]

print(fruits)

Output:

['kiwi', 'apple', 'blueberry', 'dragonfruit', 'pineapple', 'avocado', 'mango', 'grapes']

If you inject more items than you replace, the new items will be replaced where you specified, and the remaining items will move correspondingly.

In the following example, we will change the 3rd value by replacing it with two new values.

fruits = ["kiwi", "apple", "blueberry", "dragonfruit", "banana"]

fruits[2:3] = ["pineapple", "avocado"]

print(fruits)

Output:

['kiwi', 'apple', 'pineapple', 'avocado', 'dragonfruit', 'banana']

If you inject less items than you replace, the new item will be inserted where you specified, and the remaining items will move correspondingly.

In the following example, we will change the 3rd and 4th values by replacing them with one value.

fruits = ["kiwi", "apple", "blueberry", "dragonfruit", "banana"]

fruits[2:4] = ["pineapple"]

print(fruits)

Output

['kiwi', 'apple', 'pineapple', 'banana']

Add List Items

Python offers different ways to add list item values.


Append Items

You can add an item to the end of the list using the append() method.

In the following example, we will use the append() method to append a new item to the fruit list.

fruits = ["kiwi", "apple", "blueberry"]

fruits.append("banana")

print(fruits)

Output

['kiwi', 'apple', 'blueberry', 'banana']

Insert Items

To insert a new item at a specified index, you can use the insert() method.

fruits = ["kiwi", "apple", "blueberry"]

fruits.insert(1, "pineapple")

print(fruits)

Output

['kiwi', 'pineapple', 'apple', 'blueberry']

Extend List

To extend items from one list to another list, you can use the extend() method.

In the following example, we add the items from the "fruits2" list to the "fruits1" list.

fruits1 = ["kiwi", "apple", "blueberry"]
fruits2 = ["banana", "orange"]

fruits1.extend(fruits2)

print(fruits1)

Output

['kiwi', 'apple', 'blueberry', 'banana', 'orange']

The extend() method accepts any iterable object (set, tuples, dictionaries, etc.).

In the following example, we will add elements of a tuple to a list.

fruits1 = ["kiwi", "apple", "blueberry"]
fruits2 = ("banana", "orange")

fruits1.extend(fruits2)

print(fruits1)

Output

['kiwi', 'apple', 'blueberry', 'banana', 'orange']

Remove List Items

There are different ways to remove an item from a list.


Remove Specified Item

To remove a specified item from a list, you can use the remove() method.

In the following example, we will remove the "blueberry" from the "fruits" list.

fruits = ["kiwi", "apple", "blueberry", "banana", "orange"]

fruits.remove("blueberry")

print(fruits)

Output

['kiwi', 'apple', 'banana', 'orange']

Remove Specified Index

To remove a specified index from a list, you can use the pop() method.

In the following example, we will remove the 3rd item.

fruits = ["kiwi", "apple", "blueberry", "banana", "orange"]

fruits.pop(2)

print(fruits)

Output

['kiwi', 'apple', 'banana', 'orange']

When you do not pass an index to the pop() method, the pop() method will remove the last item.

fruits = ["kiwi", "apple", "blueberry", "banana", "orange"]

fruits.pop()

print(fruits)

Output

['kiwi', 'apple', 'blueberry', 'banana']

You can also remove a specified index from a list using the del keyword.

In the following example, we will remove the second item using the del keyword.

fruits = ["kiwi", "apple", "blueberry", "banana", "orange"]

del fruits[1]

print(fruits)

Output

['kiwi', 'blueberry', 'banana', 'orange']

Using the del keyword, you can delete the entire list.

In the following example, we will delete the "fruits" list.

fruits = ["kiwi", "apple", "blueberry", "banana", "orange"]

del fruits

# This will cause an error
print(fruits)

Output

NameError   Traceback (most recent call last)
      4 
      5 # This will cause an error
----> 6 print(fruits)

NameError: name 'fruits' is not defined

Clear a List

To empty a list, you can use the clear() method.

After clearing a list, the list will remain, but it will not have any content.

In the following example, we will clear the "fruits" list.

fruits = ["kiwi", "apple", "blueberry", "banana", "orange"]

fruits.clear()

print(fruits)

Output

[]

Loop Lists

In Python, there are different ways to loop through a list.


Loop Through a List using a for Loop

You can loop through a list of items with the help of a for loop.

In the following example, we will print all items on the "fruits" list.

fruits = ["kiwi", "apple", "blueberry", "banana"]

for fruit in fruits:
    print(fruit)

Output

kiwi
apple
blueberry
banana

Loop Through the Index Numbers

Python provides the possibility to loop through the list items by referring to their index number.

To create a suitable iterable, we will use the range() and len() functions.

In the following example, we will print all items by referring to their index number.

fruits = ["kiwi", "apple", "blueberry", "banana"]

for i in range(len(fruits)):
    print(fruits[i])

Output

kiwi
apple
blueberry
banana

Loop Through a List using a while Loop

It is possible to loop through the list items using a while loop.

We will use the len() method to determine the length of the list. We will start at the 0 indexes and loop through the list items by referring to their indexes.

In the following example, we will print all the "fruits" list items using the while loop.

fruits = ["kiwi", "apple", "blueberry", "banana"]

size = len(fruits)
i = 0

while i < size:
    print(fruits[i])
    i += 1

Output

kiwi
apple
blueberry
banana

Looping Through a List Using List Comprehension

List Comprehension provides the shortest syntax for looping through lists.

In the following example, we will use a short hand for loop using list comprehension to print all the "fruits" list items.

fruits = ["kiwi", "apple", "blueberry", "banana"]

[print(fruit) for fruit in fruits]

Output

kiwi
apple
blueberry
banana

List Comprehension

List Comprehension offers a shorter syntax and an elegant way to create a new list from the values of an existing list.

In the following example, we will create a new list containing only the fruits with the letter "b" in the name using the standard way and using list comprehension.

  • Without List Comprehension::

    fruits = ["kiwi", "apple", "blueberry", "banana"]
    
    new_list = []
    
    for f in fruits:
      if "b" in f:
        new_list.append(f)
    
    print(new_list)
    

    Output

    ['blueberry', 'banana']
    
  • Using List Comprehension:

    fruits = ["kiwi", "apple", "blueberry", "banana"]
    
    new_list = [f for f in fruits if "b" in f]
    
    print(new_list)
    

    Output

    ['blueberry', 'banana']
    

The Syntax

List comprehension consists of an expression followed by for statement inside square brackets [].

The return of a list comprehension is a new list. The old list stays unchanged.

new_list = [expression for item in iterable if condition == True]

Condition in Comprehension List

The condition in a comprehension list is like a filter that only accepts the items that evaluate True.

In the following example, we will create a comprehension list that only accepts items that not "banana".

fruits = ["kiwi", "apple", "blueberry", "banana"]

new_list = [f for f in fruits if f != "banana"]

print(new_list)

Output

['kiwi', 'apple', 'blueberry']

The condition in the comprehension list is optional.

In the following example, we will use a comprehension list without a condition.

fruits = ["kiwi", "apple", "blueberry", "banana"]

new_list = [f for f in fruits]

print(new_list)

Output

['kiwi', 'apple', 'blueberry', 'banana']

Iterable in Comprehension List

The iterable in a comprehension list can be any iterable object, like a tuple, list, set etc.

In the following example, we will use the range() function to create an iterable.

new_list = [x for x in range(5)]

print(new_list)

Output

[0, 1, 2, 3, 4]

You can also use a condition with the range() function.

new_list = [x for x in range(10) if x % 2 == 0]

print(new_list)

Output

[0, 2, 4, 6, 8]

Expression in Comprehension List

The expression is the current item in the iteration. It is also the result that you can manipulate before it finishes as a list item in the new list.

In the following example, we will multiply by two every item of the list.

my_list = [1, 3, 5, 7]

new_list = [ x * 2 for x in my_list]

print(new_list)

Output

[2, 6, 10, 14]

In the comprehension list, you can set the outcome of the expression to whatever you want.

In the following example, we will set all the values in the new list to 'hi'.

my_list = [1, 3, 5, 7]

new_list = [ 'hi' for x in my_list]

print(new_list)

Output

['hi', 'hi', 'hi', 'hi']

In the comprehension list, the expression can also contain conditions, not like a filter, but a way to change the outcome.

In the following example, we will change the outcome by returning "watermelon" instead of "blueberry".

fruits = ["kiwi", "apple", "blueberry", "banana"]

new_fruits = [f if f != "bleuberry" else "watermelon" for f in fruits]

print(new_fruits)

Output

['kiwi', 'apple', 'watermelon', 'banana']

Sort Lists

There are different ways to sort a list in Python.


Sort List Alphanumerically

In Python, list objects have a built-in sort() method that sorts the list alphanumerically ascending by default.

In the following example, we will sort the "fruits" list alphanumerically.

fruits = ["kiwi", "apple", "blueberry", "dragonfruit", "banana"]

fruits.sort()

print(fruits)

Output

['apple', 'banana', 'blueberry', 'dragonfruit', 'kiwi']

You can also sort a list numerically.

my_list = [96, 63, 70, 30 , 26, 46]

my_list.sort()

print(my_list)

Output

[26, 30, 46, 63, 70, 96]

Sort List in a Descending order

To sort a list in descending order, use the sort() method with the keyword argument reverse = True.

In the following example, we will sort the "fruits" list in descending order.

fruits = ["kiwi", "apple", "blueberry", "dragonfruit", "banana"]

fruits.sort(reverse = True)

print(fruits)

Output

['kiwi', 'dragonfruit', 'blueberry', 'banana', 'apple']

You can also sort a list numerically in descending order.

my_list = [96, 63, 70, 30 , 26, 46]

my_list.sort(reverse = True)

print(my_list)

Output

[96, 70, 63, 46, 30, 26]

Case Insensitive of the sort method

The sort() method is case sensitive, resulting in all capital letters being ordered before lower case letters.

Case-sensitive sorting can produce unexpected results.

fruits = ["Kiwi", "apple", "blueberry", "Dragonfruit", "banana"]

fruits.sort()

print(fruits)

Output

['Dragonfruit', 'Kiwi', 'apple', 'banana', 'blueberry']

To overcome the case sensitivity of the sort() method, you can use the built-in function as a key function when sorting a list.

To make the sort() method case-insensitive, you can use the str.lower as a key function.

In the following example, we will perform a case-insensitive sort of the "fruits" list.

fruits = ["Kiwi", "apple", "blueberry", "Dragonfruit", "banana"]

fruits.sort(key = str.lower)

print(fruits)

Output

['apple', 'banana', 'blueberry', 'Dragonfruit', 'Kiwi']

Customize Sort Function

You can make your own sorting function by passing the keyword argument key = function to the sort() method.

The customized function will return a number that will be used to sort the list (the lowest number will be in the first position and so on).

In the following example, we will sort the list based on how close the number is to 10.

def custom_sort(n):
    return abs(n -10)

my_list = [18, 16, 10, 30 , 26, 46, 6, 12]

my_list.sort(key = custom_sort)

print(my_list)

Output

[10, 12, 6, 16, 18, 26, 30, 46]

Reverse Order

Python offers the possibility to reserve the order of a list, regardless of the alphanumeric order.

The reverse() method reverses the current sorting order of the elements.

In the following example, we will reverse the order of the "fruits" list.

fruits = ["Kiwi", "apple", "blueberry", "Dragonfruit", "banana"]

fruits.reverse()

print(fruits)

Output

['banana', 'Dragonfruit', 'blueberry', 'apple', 'Kiwi']

Copy Lists

There are multiple ways to copy lists in Python.


Copy a List

When you type list2 = list1, you are not copying a list, you are just copying the reference of the list1 in the list2. So any changes that happen in the list1 will automatically also be made in list2, because both list1 and list2 reference the same list.

You can copy a list using the built-in List method copy().

In the following example, we will make a copy of the "fruits" list using the copy() method.

fruits = ["kiwi", "apple", "blueberry", "dragonfruit", "banana"]

my_list = fruits.copy()

print(my_list)

Output

['kiwi', 'apple', 'blueberry', 'dragonfruit', 'banana']

Another way to copy a list is to use the built-in method list().

In the following example, we will copy the "fruits" list using the list() method.

fruits = ["kiwi", "apple", "blueberry", "dragonfruit", "banana"]

my_list = list(fruits)

print(my_list)

Output

['kiwi', 'apple', 'blueberry', 'dragonfruit', 'banana']

Join Lists

There are different ways to join or concatenate two or more lists in Python.


Join Two Lists

One of the simplest ways to join two or more lists is to use the + operator.

In the following example, we will use the + to join two lists.

list1 = ["apple", "kiwi", "orange"]
list2 = ["a", "b", "c"]

list3 = list1 + list2

print(list3)

Output

['apple', 'kiwi', 'orange', 'a', 'b', 'c']

You can also use the append() method to join all the items from one list to another.

In the following example, we will append items in the "list2" into "list1".

list1 = ["apple", "kiwi", "orange"]
list2 = ["a", "b", "c"]

for x in list2:
    list1.append(x)

print(list1)

Output

['apple', 'kiwi', 'orange', 'a', 'b', 'c']

You can also use the extend() method to add elements from one list to another list.

In the following example, we will use the extend() method to add "list2" at the end of "list1".

list1 = ["apple", "kiwi", "orange"]
list2 = ["a", "b", "c"]

list1.extend(list2)

print(list1)

Output

['apple', 'kiwi', 'orange', 'a', 'b', 'c']

List Methods

In the following table, we will show all the methods that are available with list objects.

Method Description
append() It is used to add an item at the end of the list.
extend() It is used to add all items of a list to another list.
insert() It is used to insert an item at the specified index.
remove() It is used to remove the item with the specified value.
pop() It is used to remove and return an item at the given index.
clear() It is used to remove all items from the list.
index() It is used to return the index of the first matched item.
sort() It is used to sort items in a list in ascending order.
count() It is used to return the count of the number of items passed as an argument.
reverse() It is used to reverse the order of items in the list.
copy() It is used to return a shallow copy of the list.


ExpectoCode is optimized for learning. Tutorials and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy.
Copyright 2020-2021 by ExpectoCode. All Rights Reserved.