Python lists are extremely powerful when used correctly for storing information of the same or different data types. Lists are always created using square brackets ([]) and each element in a list is mutable. The best way to learn how to use a list is to practice! Feel free to grab the code notebook at the bottom and follow along.

# Typing our list out
list1 = [1,2,3,4,5]
print(list1)

# Creating a list by iterating through a range of numbers and appending each element to the empty list.
rng = 5 
list2 = [] 
for x in range(rng): 
list2.append(x) 
print(list2)

# Using the range() function and list comprehension to make a list 
list3 = [x for x in range(rng)]
print(list3)

# Strings can be lists
a = "konnichiwa"
print(list(a))

# Output
[0, 1, 2, 3, 4] 
[0, 1, 2, 3, 4] 
[0, 1, 2, 3, 4]
['k', 'o', 'n', 'n', 'i', 'c', 'h', 'i', 'w', 'a']

Lists can store a mixture of data types including:

  • Integers [1,2,3,4,5]
  • Floats [1.1, 2.22, 3.333, 4.4444, 5.55555]
  • Strings [โ€œHiโ€, โ€œHowโ€, โ€œAreโ€, โ€œYouโ€]
  • Lists [[1,2], [3,4], [5,6]]
  • Dictionaries [{โ€œoneโ€, 1}, {โ€œtwoโ€, 2}, {โ€œthreeโ€: 3}]
  • Variables a,b,c = 1,2,3 ---> list1 = [a,b,c]
  • A mixture of Data Types [1, โ€œaโ€, 2.22, {โ€œoneโ€:1}, [9,8,7]]

Every time you make a list in python it automatically comes with built-in methods for using it, there are some built-in functions in the python standard library that work great with lists too.

# Add an item to the end of a list
list1.append(100)
list1.append(4)
list1.append(2)
print(list1)

# Sort the list
list1.sort()
print(list1)

# Map over a list with a function
list1 = list(map(lambda x: x*-1, list1))
print(list1)

# Get the max value in a list
max_val = max(list1)
print(max_val)

# Get the minimum value in a list
min_val = min(list1)
print(min_val)

# Add all elements of a list to a single list
list1.extend([200, 300, 400])
print(list1)

# Insert an element at a specific index position
list1.insert(0, "ABC")
print(list1)

# Remove the first value in a list equal to user input
list1.remove(-100)
print(list1)

# Return the index location of an element or list of elements
list1.index(0)

# Return the number of elements in a list
length = len(list1)
print(length)

# Return the number of times an element appears
count = list1.count(-4)
print(count)

# Reverse the order of the list
list1.reverse()
print(list1)

# Output
[0, 1, 2, 3, 4, 100, 4, 2]
[0, 1, 2, 2, 3, 4, 4, 100]
[0, -1, -2, -2, -3, -4, -4, -100] 
0 
-100 
[0, -1, -2, -2, -3, -4, -4, -100, 200, 300, 400] 
['ABC', 0, -1, -2, -2, -3, -4, -4, -100, 200, 300, 400] 
['ABC', 0, -1, -2, -2, -3, -4, -4, 200, 300, 400] 
11 
2 
[400, 300, 200, -4, -4, -3, -2, -2, -1, 0, 'ABC']

Slicing

Making lists is powerful especially since they can hold a variety of data types. With slicing, we can choose the exact element or selection of elements we want. We can even slive in reverse order using negative indexing. Letโ€™s try it out.

Single Element Slicing

Python uses zero-based indexing. This means that all lists start at 0 instead of 1! If you wanted to grab the first element in your list you would zero instead of one and count upwards from there until the end of your list. Indexing also helps us write better code that is reusable.

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

# Indexing the first element
print(list4[0])

#Indexing the last element
print(list4[4])

# Indexing the first element negatively
print(list4[-5])

# Indexing the last element negatively
print(list4[-1])

# Indexing the 5th element (Will return an error)?
print(list4[5])

# Output
1
5
1
5
--------------------------------------------------------------------IndexError                                Traceback (most recent call last)
<ipython-input-8-897f86db10fb> in <module>()
      8 
      9 # Indexing the 5th element?
---> 10 list4[5]
IndexError: list index out of range

As we can see, using an index value outside the zero-based index range of the list returns an error. This makes sense because there is no value at index 5 and thus no index value 5

Using negative indexing we can see that each element in the list has 2 possible index values. Using -1 returns the last element and further elements can be negatively indexed by continuing to countdown from -1.

Multi-Element Slicing

list5 = [x for x in range(10)]
print(list5)

# list5[:] - returns the entire list
print(list5[:])

# list5[start:stop] - all elements from "start" to "stop"-1
print(list5[0:5])

# list5[start:]  - all elements from start to end of list
print(list5[5:])

# list5[:stop] - all elements from the start of list to the stop-1
print(list5[:5])

# Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
[0, 1, 2, 3, 4] 
[5, 6, 7, 8, 9] 
[0, 1, 2, 3, 4]

Using Negative Index Slicing

We can perform all the normal slicing techniques weโ€™ve learned using negative indexing too!

# Return the first element
print(list5[-10])

# Return the last element
print(list5[-1])

# Return the entire list
print(list5[-10:])

# Return the last 5 elements
print(list5[-5:])

# Return the first 5 elements
print(list5[-10:-5])

# Output
0 
9 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
[5, 6, 7, 8, 9] 
[0, 1, 2, 3, 4]

Using List Slicing and Stepping

Stepping through your list gives you the power to choose every 2nd, 3rd, 4th, etc. element in a list. The syntax looks like the following:

list5[start:stop:step]

Lets practice!

# Return every other element
print(list5[::2])

# Return every 3rd element
print(list5[::3])

# Return every 4th element starting from 4
print(list5[4::4])

# Return the list in reverse order
print(list5[::-1])

# Return every other element in reverse
print(list5[::-2])

# Output
[0, 2, 4, 6, 8] 
[0, 3, 6, 9] 
[4, 8] 
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0] 
[9, 7, 5, 3, 1]

List Comprehensions

List comprehension makes it easy to create a list using the python range() function or another list. You can even use compound statements in a list comprehension to fine-tune your output. Iโ€™ve already used some list comprehensions to show you how intuitive they can be.

# Simple List comprehension
list6 = [x for x in range(10)]
print(list6)

# Simple arithmetic using list comprehension
list7 = [x+100 for x in range(10)]
print(list7)

# Using an "if" statement to select even numbers
list8 = [x for x in range(10) if x%2 == 0]
print(list8)

# Using "if-else" statments
list9 = [x if x%3 == 0 else "X" for x in list6]
print(list9)

# Creating a list of lists from a list
list10 = [[x, x+1, x+2] for x in list8]
print(list10)

# Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
[100, 101, 102, 103, 104, 105, 106, 107, 108, 109] 
[0, 2, 4, 6, 8] 
[0, 'X', 'X', 3, 'X', 'X', 6, 'X', 'X', 9] 
[[0, 1, 2], [2, 3, 4], [4, 5, 6], [6, 7, 8], [8, 9, 10]]

Thatโ€™s a lot to take in!

Learning how to use a list properly has made me a better coder and has also made my code more readable for others. There is still more to learn, but I hope these initial notes about lists will help propel your understanding to new heights.

Find the code for this blog here!

Iโ€™m always looking for feedback, so please leave a comment if you see an error.