Lists

Introduction to Python for Developers

George Boorman

Curriculum Manager, DataCamp

Problem

# Variables of product prices
price_one = 10
price_two = 20
price_three = 30
price_four = 15
price_five = 25
price_six = 35
Introduction to Python for Developers

Lists to the rescue!

  • List = store multiple values in a single variable
    • Can contain any combination of data types e.g., str, float, int, bool

 

# List of prices
prices = [10, 20, 30, 15, 25, 35]
# List of prices using variables as values
prices = [price_one, price_two, price_three,
          price_four, price_five, price_six]
Introduction to Python for Developers

Checking the data type

# Check the data type of a list
type(prices)
<class 'list'>
# Check the data type of a string
type("Hello")
<class 'str'>
Introduction to Python for Developers

Accessing elements of a list

# Print all values in the list variable
print(prices)
[10, 20, 30, 15, 25, 35]
  • Lists are ordered
    • Can use subsetting or indexing
    • Python counts values starting from zero for the first element
Introduction to Python for Developers

Accessing elements of a list

  • List = []
  • Subsetting = a_list[index]
prices = [10, 20, 30, 15, 25, 35]

# Get the value at the first index
prices[0]
10
# Get the value at the fourth index
prices[3]
15
Introduction to Python for Developers

Finding the last element in a list

prices = [10, 20, 30, 15, 25, 35]

# Get the last element of a list
prices[5]
35
# Get the last element of a list
prices[-1]
35
Introduction to Python for Developers

Accessing multiple elements

prices = [10, 20, 30, 15, 25, 35]

# Access the second and third elements
prices[1:3]
[20, 30]
  • [starting_element:last_element + 1]
  • Add one to the last element's index because:
    • Python returns everything up to but not including that index
Introduction to Python for Developers

Accessing multiple elements

# Access all elements from the fourth index onwards
prices[3:]
[15, 25, 35]
# Get the first three elements
prices[:3]
[10, 20, 30]
Introduction to Python for Developers

Alternating access

# Access every other element
prices[::2]
[10, 30, 25]
# Access every third element, starting at the second
prices[1::3]
[20, 25]
Introduction to Python for Developers

Lists cheat sheet

Syntax Functionality
a_list = [1, 2, 3, 4, 5, 6] Create a list variable
a_list[0] Get the first element at index zero
a_list[-1] Get the last element
a_list[0:3] Get the first, second, and third elements
a_list[:3] Get the first, second, and third elements
a_list[2:] Get all elements from the third index onwards
a_list[::2] Get every other element from the first index onwards
Introduction to Python for Developers

Let's practice!

Introduction to Python for Developers

Preparing Video For Download...