DEV Community

Nelson Figueroa
Nelson Figueroa

Posted on • Originally published at nelson.cloud on

Python Lists Cheatsheet

This is yet another cheatsheet I made for myself when studying for Leetcode and Hackerrank kinds of interviews. It's organized in a way that makes sense to me.

I previously made a Ruby Arrays Cheatsheet you can check out.

All examples were tested using the Python 3.12.3 REPL.

Initializing a List

Empty List

my_list = []
Enter fullscreen mode Exit fullscreen mode

List with Elements

Initializing a list of integers:

my_list = [1, 2, 3, 4, 5]

print(my_list)
# [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Initializing a list of strings:

my_list = ["A", "B", "C"]
# ['A', 'B', 'C']
Enter fullscreen mode Exit fullscreen mode

You can mix different types of elements:

my_list = [1, "A", [2, 3], {"my_key": "my_value"}]

print(my_list)
# [1, 'A', [2, 3], {'my_key': 'my_value'}]
Enter fullscreen mode Exit fullscreen mode

Adding Elements

At the Beginning of a List

We can also use insert() to add elements to the beginning of a list by specifying index 0:

my_list = [1, 2, 3]
my_list.insert(0, 4)

print(my_list)
# [4, 1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

At the End of a List

Use append() to add an element to the end of a list:

my_list = [1, 2, 3]
my_list.append(4)

print(my_list)
# [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

At a Specific Index

Use insert() and specify the index and element to add:

my_list = ["A", "B", "C"]
my_list.insert(1, "D")

print(my_list)
# ['A', 'D', 'B', 'C']
Enter fullscreen mode Exit fullscreen mode

Removing Elements

At the Beginning of a List

We can use del() and specify index 0. This modifies the list in-place:

my_list = [1, 2, 3, 4]
del(my_list[0])

print(my_list)
# [2, 3, 4]

del my_list[0]

print(my_list)
# [3, 4]
Enter fullscreen mode Exit fullscreen mode

At the End of a List

We can use pop(). Modifies list in-place:

my_list = [1, 2, 3]
my_list.pop()

print(my_list)
# [1, 2]
Enter fullscreen mode Exit fullscreen mode

We can also use del() and specify the last index, which should be len(list) - 1, but using pop() is a bit cleaner in my opinion.

At a Specific Index

Similar to removing an element from the beginning of the list, except we pass in a different index aside from 0:

my_list = ['A', 'B', 'C', 'D']
del(my_list[2])

print(my_list)
# ['A', 'B', 'D']
Enter fullscreen mode Exit fullscreen mode

Retrieving Elements

The First Element

There's no bult-in Python method to get the first element as far as I know, just specify index 0 like in most programming languages:

my_list = ['A', 'B', 'C', 'D']
char = my_list[0]

print(char)
# 'A'
Enter fullscreen mode Exit fullscreen mode

The Last Element

Use index -1 to get the last element of a list. Negative indices start at the end of the list.

my_list = ['A', 'B', 'C', 'D']
char = my_list[-1]

print(char)
# 'D'
Enter fullscreen mode Exit fullscreen mode

Element at a Specific Index

Similar to other programming languages, specify an index:

my_list = ['A', 'B', 'C', 'D']
char = my_list[2]

print(char)
# 'C'
Enter fullscreen mode Exit fullscreen mode

Sorting Lists

We can use sort() to sort a list. This modifies the list in-place:

my_list = [4, 5, 1, 3, 2]
my_list.sort()

print(my_list)
# [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

We can also use sorted(). This returns a new list and does not modify the original list:

my_list = [4, 5, 1, 3, 2]
sorted_list = sorted(my_list)

print(my_list)
# [4, 5, 1, 3, 2]

print(sorted_list)
# [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Looping Through Lists

Each Element

Use for <element> in <list_name> syntax:

my_list = ['A', 'B', 'C', 'D']

for char in my_list:
    print(char)

# output:
# A
# B
# C
# D
Enter fullscreen mode Exit fullscreen mode

Each Index

Use range() and len() to loop through a list's indices:

my_list = ['A', 'B', 'C', 'D']

for index in range(len(my_list)):
    print(index)

# output:
# 0
# 1
# 2
# 3
Enter fullscreen mode Exit fullscreen mode

Element and Index

Use enumerate() to loop through both elements and indices:

my_list = ['A', 'B', 'C', 'D']

for index, element in enumerate(my_list):
    print(f'Index: {index}, Element: {element}')

# output:
# Index: 0, Element: A
# Index: 1, Element: B
# Index: 2, Element: C
# Index: 3, Element: D
Enter fullscreen mode Exit fullscreen mode

Other Things to Know

Lists vs Arrays

Note that there are both Arrays and Lists in Python. Arrays are saved contiguously in memory and have fixed sizes so they are faster for reading but insertion and deletion costs are high. Arrays can only have elements of the same type.

Lists are more flexible. Lists can have elements of different types and do not have fixed sizes. The flexibility of Lists results in more memory being used by these data structures.

Here's an example of an Array of integers being created in Python.

import array

# requires a more verbose syntax compared to a List
a = array.array('i', [1, 2, 3, 4, 5])

print(a)
# array('i', [1, 2, 3, 4, 5])
Enter fullscreen mode Exit fullscreen mode

Attempting to add an element that doesn't match the type of the existing elements results in an error:

import array

a = array.array('i', [1, 2, 3, 4, 5])
a.append("str")

# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: 'str' object cannot be interpreted as an integer
Enter fullscreen mode Exit fullscreen mode

Appending elements of the same type will work as expected:

import array

a = array.array('i', [1, 2, 3, 4, 5])
a.append(6)

print(a)
# array('i', [1, 2, 3, 4, 5, 6])
Enter fullscreen mode Exit fullscreen mode

You can learn more about Arrays in this GeeksForGeeks article.

Reversing a List

We can reverse a list using this syntax. This does not modify a list in-place, it returns a new list:

my_list = [1, 2, 3, 4, 5]
reversed = my_list[::-1]

print(my_list)
# [1, 2, 3, 4, 5]

print(reversed)
# [5, 4, 3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

We can also use sort(reverse=True) to reverse a list. This modifies the list in-place:

my_list = [1, 2, 3, 4, 5]
my_list.sort(reverse=True)

print(my_list)
# [5, 4, 3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

References

Top comments (1)

Collapse
 
michaeltharrington profile image
Michael Tharrington

Oh heck yes!! Love these kinda cheatsheets... they're so handy. 🙌

By the way, just to note we have a built-in feature that allows folks to create a series on DEV. If you're interested, here's an article that explains how:

I was thinking about your Ruby Arrays cheatsheet and figured you might wanna put the different cheatsheets you've created into a series. Just a suggestion, def not necessary and totally up to you!

Hope this info is helpful and thanks for sharing this awesome post!