How to Use Lists in Python

Reading Time: 5 Minutes
Publication date:
Last updated:

We learn to add and modify items, concatenate and copy lists.

In statically-typed languages, there are predefined types: characters, numbers, or classes. They also have collections — arrays, lists, and other data structures — which consist of elements with fixed or dynamic dimensions.

When a variable is declared as an object, some space is reserved by the operating system. For example, a string of four characters occupies eight bytes. Each character addresses a memory location in the operating system, and the string is an array of these addresses. In C-style languages, arrays are created with a specific size for the type of object. In Python, there are no restrictions on the type or dimension of list elements. That is, in Python, a list is a dynamic information collection.

How to solve common problems

Declare a list

Syntax for creating a list in Python:

Mylst — the name of the variable. Elements are specified in brackets.

Python has a built-in function list(). This function either creates an empty list or converts an iterable into a list. To create an empty list object using the function, write:

mylist = list()

Access an element

Lists are collections of elements. To access them, their index — a sequential number — is used. Unlike, for example, a dictionary, which allows access to values by key. The index of the first element is 0, the second is 1, the third is 2.

To access the fifth element of the list:

mylst = [1, 2, 3, 4, 5]
print(mylst[4])  # Will print 5.

Add an element

You can do this using the built-in append() function:

mylst = [1, 2, 3, 4, 5]
mylst.append(6)
print(mylst)  # Will print [1, 2, 3, 4, 5, 6].

You can also use the insert() method, which accepts two arguments — the index and the value:

mylst = [1, 2, 3, 4, 5]
mylst.insert(1, 25)
print(mylst)  # Will print [1, 25, 2, 3, 4, 5].

Modify an element

Set a new value at its index:

mylst = [1, 2, 3, 4, 5]
mylst[1] = None
print(mylst)  # Will print [1, None, 3, 4, 5].

In Python, elements of a collection do not need to be of the same type.

Remove an element

You can use the built-in del() function:

mylst = [1, 2, 3, 4, 5, 4, 3, 2, 1]
del mylst[2]
print(mylst)  # Will print [1, 2, 4, 5, 4, 3, 2, 1].

Or use the remove() method:

mylst = [1, 2, 3, 4, 5, 4, 3, 2, 1]
mylst.remove(2)
print(mylst)  # Will print [1, 3, 4, 5, 4, 3, 2, 1].

Check for an element’s presence

To check if a specific element exists in the list, use in:

mylst = [1, 2, 3, 4, 5]
print(None in mylst)  # Will print False.
print(3 in mylst)  # Will print True.

Concatenate lists

Use the extend() method:

mylst = [1, 2]
mylst1 = [3, 4]
mylst2 = [5]
mylst.extend(mylst1)
print(mylst)  # [1, 2, 3, 4]
mylst.extend(mylst2)
print(mylst)  # [1, 2, 3, 4, 5]

Or the + operator:

mylst = [1, 2]
mylst1 = [3, 4]
mylst2 = [5]
mylst += mylst1
print(mylst)  # [1, 2, 3, 4]
mylst += mylst2
print(mylst)  # [1, 2, 3, 4, 5]

Copy a list

You can use the copy() method:

mylst = [1, 2, 3, 4, 5]
mylst_copy = mylst.copy()
print(mylst)  # Will print [1, 2, 3, 4, 5].
print(mylst_copy)  # Will print [1, 2, 3, 4, 5].

Or make a full slice:

mylst = [1, 2, 3, 4, 5]
mylst_copy = mylst[::]
print(mylst)  # Will print [1, 2, 3, 4, 5].
print(mylst_copy)  # Will print [1, 2, 3, 4, 5].

Iterate over a list

Using a for loop:

mylst = [1, 2, 3, 4, 5]
for item in mylst:
    print(item)
# 1
# 2
# 3
# 4
# 5

Or using a while loop:

mylst = [1, 2, 3, 4, 5]
i = 0
while True:
    try:
        print(mylst[i])
    except IndexError:
        print("Done!")
        break
    i += 1
# 1
# 2
# 3
# 4
# 5
# Done!

List methods

index: Get the index of an element:

mylst = [1, 2, 3, 4, 5, 4, 3, 2, 1]
print(mylst.index(3))  # Will print 2.

count: Get the number of occurrences of an element:

mylst = [1, 2, 3, 4, 5, 4, 3, 2, 1]
count_for_one = mylst.count(1)
print(count_for_one)  # Will print 2.
count_for_five = mylst.count(5)
print(count_for_five)  # Will print 1.

clear: Clear all elements from the list:

mylst = [1, 2, 3, 4, 5]
mylst.clear()
print(mylst)  # Will print [].

sort: Sort the list based on specified keys. It accepts two optional arguments: key and reverse:

mylst = [1, 3, 2, 4, 5]
mylst.sort()
print(mylst)  # Will print [1, 2, 3, 4, 5].

reverse: Reverse the order of the list elements:

mylst = [1, 2, 3, 4, 5]
mylst.reverse()
print(mylst)  # Will print [5, 4, 3, 2, 1].

pop: Retrieve and remove an element from the list. It accepts an optional index argument, defaulting to the last element:

mylst = [1, 2, 3, 4, 5]
x = mylst.pop()
print(x)  # Will print 5.
print(mylst)  # Will print [1, 2, 3, 4].
y = mylst.pop(2)
print(y)  # Will print 3.
print(mylst)  # Will print [1, 2, 4].

Built-in functions

Get the length of any collection: Use the len() function:

mylst = [1, 2, 3, 4, 5]
list_length = len(mylst)
print(list_length)  # Will print 5.

Return the element with the maximum value: Use the max() function:

mylst = [1, 2, 3, 4, 5, 4, 3, 2, 1]
max_value = max(mylst)
print(max_value)  # Will print 5.

Return the element with the minimum value: Use the min() function:

mylst = [1, 2, 3, 4, 5]
min_value = min(mylst)
print(min_value)  # Will print 1.

Type casting

You can create a list from any iterable object by passing it to the list() function. This object can be a string, set, tuple, or generator:

myset = {1, 2, 3, 4}
mytuple = (5, 6)
mystring = "Test string"
lst1 = list(myset)
lst2 = list(mytuple)
lst3 = list(mystring)
print(lst1)  # Will print [1, 2, 3, 4].
print(lst2)  # Will print [5, 6].
print(lst3)  # Will print ['T', 'e', 's', 't', ' ', 's', 't', 'r', 'i', 'n', 'g'].

Slicing operations

Slicing can be used to create new lists from an existing list. You can get a full copy or some elements by specifying the start and end indices:

mylst = [1, 2, 3, 4, 5]
mylst_slice_0 = mylst[::]
print(mylst_slice_0)  # Will print [1, 2, 3, 4, 5].
mylst_slice_1 = mylst[0:2]
print(mylst_slice_1)  # Will print [1, 2].
mylst_slice_2 = mylst[::2]
print(mylst_slice_2)  # Will print [1, 3, 5].

List comprehensions

This construct allows easy creation of lists:

mylst = [_ for _ in range(6)]
print(mylst)  # Will print [0, 1, 2, 3, 4, 5].

You can specify conditions for element generation:

mylst = [x if x % 2 == 0 else "odd" for x in range(20)]
print(mylst)  # Will print [0, 'odd', 2, 'odd', 4, 'odd', 6, 'odd', 8, 'odd', 10, 'odd', 12, 'odd', 14, 'odd', 16, 'odd', 18, 'odd'].

Key Points About Lists

  • Lists are ordered collections of elements. In Python, all elements of a list do not need to be of the same type.
  • Lists are created using the list() function, list comprehensions, or slicing.
  • List methods: insert() to add elements, remove() to delete elements, extend() to concatenate, copy() to copy. Also, index(), sort(), and others.
  • Python has integrated functions for working with objects. For example, del(), list(), len(), max(), min().

5 / 5. 2

Share:

Leave a comment