Python Lists – Learn Data Structures in Python

Lists are a built-in data structure in Python which allows you to store data of various types. According to the python docs, lists typically store homogeneous elements but varying data types are allowed. A non-technical way to look at lists is to associate them with the list we create in everyday life. A cook may have a list of recipes they need to assemble from a framer market which helps them craft their delicious recipe.

A bartender may need a list of ingredients to create their award winning craft cocktail, and a child may have a Christmas list of all of the items they want from Santa; the list goes on (cheesy pun) . A list in python is a flexible. Like lists in everyday life, the lists in python can be mutated (a fancy word for modified). A list in python can also be sliced (a range of elements returned), and indexed (elements mapped to a corresponding value ). Lists in python comes equipped with a myriad of operations and functions that allow them to be manipulated further.

How to create a list in python

The below code snippet shows how to create a simple list in python:

a = [1, 10, 20, 25, 38, 45.27, 57, 100, 200]

Here’s a diagram to illustrate how this works:

list diagram in python


List diagram in python

Lists in python are created with comma separated values which are enveloped within square brackets. A list can contain varying data types like integers, floating points, strings, and containers including other lists. Like strings and tuples, a list is a sequence type and therefore supports similar operators. Let’s explore some of the list operations in python such as indexing, slicing, in, not in, and len().

How List Indexes Work

As shown in the List diagram in python, lists can have both positive and negative indexes. To access the value of the corresponding index, use subscription notation which is shown below:

print(a[0])
print(a[-1])
1
57

How to Slice Lists

Lists can also be sliced, or a sequence of specific elements extracted. The notation used for slicing is similar to indexing, with the exception that colons are used to indicate what indexes you want to slice from.

print(a[0:2])
print(a[::2])
print(a[2:-4])
print(a[-5])
print(a[3: -2])
print(a[:: -1])
print(a[::-2])
[1, 10]
[1, 20, 38, 57]
[20]
20
[25, 38]
[57, 45.27, 38, 25, 20, 10, 1]
[57, 38, 20, 1]

Common List Operations

Common list operators are used for membership testing (in, not in), determining the length of a list (len), concatenating or joining a list with other elements (+), and multiplying a list (*). Code fragments to showcase these operators are shown below:

a = [1, 2, 3]
b = [100, 200, 300]
c = a + b
d = a * 3
e = ['apple', 'sony', 'dell', 'hp']
f = ['samsung', 'nokia', 'LG', 'HTC']

print('{} is in {}? {}'.format(200, b, 200 in b))
print('{} not in {}? {}'.format(100, a, 100 not in a))
print('The length of {} is {}'.format(a, len(a)))
print('The length of {} is {}'.format(a * 3, len(a * 3)))
print('{} + {} = {}'.format('e', 'f', e + f))
print('c = {}'.format(c))
print('d = {}'.format(d))
200 is in [100, 200, 300]? True
100 not in [1, 2, 3]? True
The length of [1, 2, 3] is 3
The length of [1, 2, 3, 1, 2, 3, 1, 2, 3] is 9
e + f = ['apple', 'sony', 'dell', 'hp', 'samsung', 'nokia', 'LG', 'HTC']
c = [1, 2, 3, 100, 200, 300]
d = [1, 2, 3, 1, 2, 3, 1, 2, 3]

Built-in list functions in python3.0+

Python makes it convenient to manipulate lists with the list class which contains a plethora of methods. You can view all of the list methods on the python docs.

The below code fragments gives a demo of some of these methods.

f = [10, 20, 30, 40, 50]
a = f.index(50)
b = f.count(0)
c = f.pop()
e = f.insert(2, 25)

print('f = {}'.format(f))
print('f.index(1) = {}'.format(a))
print('f.count(0) = {}'.format(b))
# reverses elements, doesn't return anything
f.reverse()
print('f reversed = {}'.format(f))
f.sort()
print('f sorted = {}'.format(f))
f.append('abc')
print('g = {}'.format(f))
# delete first element in list
del f[0]
print('f = {}'.format(f))
# delete all elements in list
del f[::]
print('f = {}'.format(f))
# delete the list as a whole
del f
f = [10, 20, 25, 30, 40]
f.index(1) = 4
f.count(0) = 0
f reversed = [40, 30, 25, 20, 10]
f sorted = [10, 20, 25, 30, 40]
g = [10, 20, 25, 30, 40, 'abc']
f = [20, 25, 30, 40, 'abc']
f = []

The list constructor

There’s a builtin list() function in python which can be used to convert iterable types (string, tuple,set, dictionary) into a list. An example of it in action is indicated below:

movie = 'Indiana Jones'
print("'movie' converted to a list is {} with len = {}".format(list(movie),
                                                              len(list(movie))))
'movie' converted to a list is ['I', 'n', 'd', 'i', 'a', 'n', 'a', ' ', 'J', 'o', 'n', 'e', 's'] with len = 13

Working with Multidimensional lists

Lists can be nested, or a list included within a list. Below is an example that shows how to use some of the functionality of a list in python.

nums = [1, 3, 5, 7, [2, 4, 6, 8, [10, 20, 30, 40]]]
print('nums = {}'.format(nums))
print('nums[{}] = {}'.format(0, nums[0]))
print('nums[{}] = {}'.format(1, nums[1]))
print('nums[{}][{}] = {}'.format(4, 0, nums[4][0]))
print('nums[{}][{}] = {}'.format(4, 1, nums[4][1]))
print('nums[{}][{}] = {}'.format(4, 2, nums[4][2]))
print('nums[{}][{}] = {}'.format(4, 3, nums[4][3]))
print('nums[{}][{}] = {}'.format(4, 4, nums[4][4]))
#print('nums[{}][{}] = {}'.format(4, 5, nums[4][5])) out of range!
nums = [1, 3, 5, 7, [2, 4, 6, 8, [10, 20, 30, 40]]]
nums[0] = 1
nums[1] = 3
nums[4][0] = 2
nums[4][1] = 4
nums[4][2] = 6
nums[4][3] = 8
nums[4][4] = [10, 20, 30, 40]

Looping over lists in python3.0

You can use any of the built-in loop constructs in python to iterate over a list in python. However, the for loop is the popular choice when it comes to iterating over collections. You can also use the enumerate() function which helps you keep track of the indices.

items = ['orange', 'pens', 'notebook', 'water bottle', 't-shirt']
for x in items:
    print(x)
orange
pens
notebook
water bottle
t-shirt
# keep track of index with enumerate
for x, y in enumerate(items):
    print('x = {} : y = {}'.format(x, y))
x = 0 : y = orange
x = 1 : y = pens
x = 2 : y = notebook
x = 3 : y = water bottle
x = 4 : y = t-shirt
count = 0
while count < len(items):
    print('count at {} = {}'.format(count, items[count]))
    count += 1
count at 0 = orange
count at 1 = pens
count at 2 = notebook
count at 3 = water bottle
count at 4 = t-shirt

List Comprehensions

List comprehensions are in essence a more concise way to create lists. There’s a couple of situations in which you would want to use them. Lets first think of a simple problem. Let’s say that you have a list, X, and that you want to quadruple the items in that list. How would you do that? Well, you could accomplish this by doing the following steps:

1) Create an empty list Y
2) Iterate over the list X
3) Multiply each element in list X by 4
4) Append each modified element of list X to Y

Below is an implementation of the above steps:

x = [100, 5, 10, 20, 26, 27993, 28]

y = []
for element in x:
    element *= 4
    y.append(element)

However, while the above is correct it can also be accomplished using a list comprehension in a single statement as shown below:

result = [element * 4 for element in x]

The basic syntax for a list comprehension is as follows:

[  for item in list if conditional]

Another use case for list comprehensions is say that you want to create a list of integers of an arbitrary length. We could easy do this that typing each variable like in the following example:

result = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

However, we can accomplish the same thing with more concise code with the help of list comprehensions.

result = [x for x in range(21)]

List comprehensions are also useful if you want to filter out certain numbers in a range. For example, let's say that you want to generate all of the numbers from 1-100 that’s greater than 50 and divisible by 2. How would you do that? This can easily be accomplished by list comprehensions as indicated below:

result = [x for x in range(1, 101) if x > 50 and x % 2 == 0]

List comprehensions can also be nested, or one list included inside another one like in the following example:

result = [[x, y] for x in range(5) for y in range(x + 1)]
[[0, 0], [1, 0], [1, 1], [2, 0], [2, 1], [2, 2], [3, 0], [3, 1], [3, 2], [3, 3], [4, 0], [4, 1], [4, 2], [4, 3], [4, 4]]

Lastly, you can apply a function to all of the elements in a list via list comprehensions. The following code snippet generates a list of length 10, and generates random numbers within the range of 1-1000 to populate the list. The code fragment is shown below:

ran1 = [random.randint(1, 1000) for x in range(10)]

Possible output. Your numbers will vary:

[242, 911, 963, 470, 975, 782, 628, 854, 329, 7]
============================================================================ Want to learn how to use Python's most popular IDE Pycharm? In the free pdf guide "Getting the Hang of PyCharm" you'll learn all of the amazing features in PyCharm along with how to get started with data science. Subscribe to the Purcell Consult newsletter and get started A.S.A.P.