Python List vs Dictionary: Which Data Type is Better? [Runtime Tests Included]

All programmers, at some point, pit Python list vs dictionary against each other to see which data type reigns supreme. Today, we'll carefully analyze both Python data types to finally answer which one you should use in your next project!
python list vs dictionary

Comparing a Python list vs dictionary is a task as common as coding loops, especially among coders learning the ropes. They are, after all, two different data types with unique implementations and strengths.

Choosing a side in a list vs dictionary Python discussion ultimately comes down to understanding each data type, how it works, and ultimately what it can do for you and your next project. Once you have those fundamentals down to the letter, making a choice is, for the most part, incredibly easy.

Python List vs Dictionary

When comparing a Python list vs dictionary you’ll want first to consider how they represent data. Lists tend to represent data collections of the same type or function, while dictionaries represent individual data with unique properties. As projects increase in complexity, you’ll often find that you’ll need a combination of these two robust data structures to create valuable apps and scripts for you and your clients. However, you’ll also need to weigh other factors, such as overall lookup speed and resource management.

Today, we’ll cover the fundamental differences and time complexity nuance that will help you pick the right choice in any Python list vs Dictionary discussion. We’ll also delve a little deeper to truly understand when you should use a list and when you should use a Python Dictionary for your projects.

Without further ado, let’s begin!

List vs Dictionary Python

Most list vs dictionary python discussions are settled with a strong understanding of each data type fundamentals, so let’s start with that. The list data type contains multiple values in an ordered sequence, with all of these items representing a collection of data from a similar type (or function). You can define a list using square brackets and separating each item with a comma, as follows:

## List example #1

['burger', 'pizza', 'pasta', 'bacon omelette']
food = ['burger', 'pizza', 'pasta', 'bacon omelette']

Each item in your list is delimited by a comma and can be accessed by referencing its respective index, as seen below.

food = ['burger', 'pizza', 'pasta', 'bacon omelette']
for i in range(len(food)):
    print('Index ' + str(i) + ' in the food list is: ' + food[I])

## Output

Index 0 in the food list is: burger        
Index 1 in the food list is: pizza
Index 2 in the food list is: pasta
Index 3 in the food list is: bacon omelette

This organized catalog of each list item is a big reason why most list vs dictionary Python discussions can be so heated. It seems ideal for iterative processes and is intuitive in nature, making it a strong choice for a wide range of projects that require sequentially-ordered data.

On the other corner of this list vs dictionary python argument, we got the Python Dictionary. A Python dictionary consists of an unordered collection of data values, which allows you to pair one item to another in any order of your choosing. They’re typically known as associative arrays since you can link a key with a specific value.

To create a Python dictionary, assign a name to it and open a pair of curly braces to store as many key-value pairs as you’d like. You can separate a key from its value with a colon and delimit each pair with a comma.

## Dictionary Example

dictionary_one = {
    "A": 1,
    "B": "2",

Beginner coders will often think that dictionaries are not proper organizational tools because they don’t follow a strictly sequential order, but that couldn’t be farther from the truth. Dictionaries store individual pieces of data with multiple properties, but each key corresponds to a specific value. This specificity and its hash table implementation turn dictionaries into compelling data structure elements for many projects.

You can even append dictionaries to dataframes in Python, which follow a strict data organization scheme you can visualize in well-organized tables. There’s tons of creative freedom around dictionaries, with values taking the forms of individual dictionaries, if need be.

Now that we understand what each element brings to the table, it’s time to map out their differences to better understand when we should use each Python data type.

Python List vs Dict

Now that we’ve covered the basics, it’s time that we go a level deeper in this Python vs dict breakdown. Let’s list (no pun intended) some of the most notable differences between these two valuable data types. We’ve already established that lists are a collection of ordered values that work like arrays, while dictionaries are unordered key-value pairs, but dictionaries are also considered hashed structures.

A hash table is an associative array that allows you to store a collection of key-value pairs. As an astute commenter on StackOverflow pointed out, asking what the difference between a hash table and a Python dictionary is, is like asking what’s the difference between a car and a Ford Focus. Dictionaries are implemented as hash tables in Python and work with hash functions, so they’re the same.

To some, this might be a borderline nit-picky observation. Still, this is a crucial difference once you consider the lookup speed differences between elements and their space-time tradeoff (which we’ll explore later in this article). But, for now, let’s get back to our Python list vs dict breakdown.

When it comes to Syntax and index types, both elements are wildly different. Lists require you to place their items inside square brackets, while dictionaries use curly brackets and their respective function. Both data structures have comma-delimited items, but dictionaries additionally need a colon that defines key-value pairs. Here’s an example that illustrates these syntactical differences:

## Dictionary Example

dictionary_one = {      ## Opening Curly Brackets
    "A": 1,             ## Key-Value pairs are separated by a colon (:)
    "B": "2",           ## Key-Value pairs are comma-delimited
    }                   ## Closing Curly Brackets

## List example

food = ['burger',             ## Opening Brackets
        'pasta',              ## items in a list are comma-delimited
       ]                      ## Closing Brackets]

Any Python list vs dict comparison needs to address how items are accessed. You can access items in your lists through their individual index values, which are assigned on creation, starting from 0. On the other hand, dictionaries require you to reference their keys to get specific values that follow no numbered order.

Last but not least, it’s important to point out that while both data structures are mutable, only lists accept true duplicates. Dictionaries, on the other hand, require all keys to be unique. Dictionary values can be duplicates, but they’re not true duplicates since their corresponding key has to be unique.

Now, let’s peel another layer in our Python list vs dict breakdown and take a look at lookup speed and resource management differences between these two data structures.

Dictionary vs List Python: Which One is Faster

When making a dictionary vs list Python comparison, you’re guaranteed to run into Big O, time complexity, and memory efficiency. Once you’re processing large amounts of data (the whole point behind automation and coding), you’ll want to use data structures and functions that will, ideally, decrease runtime and resource usage over time.

You’ll notice that, depending on the size of the input, your overall runtime can increase, and programmers use Big O notation and Time Complexity to calculate this relationship. The most common time complexity relationships are linear, constant, and quadratic.

  1. A linear time relationship means that your runtime increases as the number of input increases. This is known as O(n) in Big O notation.
  2. A constant time relationship means that the time to complete a function (runtime) does not increase when the input size varies. This is known as O(1) in Big O notation.
  3. A quadratic time relationship means that your runtime will behave like a quadratic function when the size input varies, meaning it’ll increase exponentially. This is known as O(n²) in Big O notation.

I ran some rudimentary tests to compare runtimes between a dictionary vs list Python to see where they fall under time complexity and Big O measurements. Let’s start with lists.

import time

small_list = list(range(100000))
large_list = list(range(1000000))

start_time = time.time()
for i in small_list:
    if i == 99999:
completed_time = time.time() - start_time
print (f'Searching Small List: {completed_time} seconds')

start_time_1 = time.time()
for i in large_list:
    if i == 999999:
completed_time_2 = time.time() - start_time_1
print (f'Searching Large List: {completed_time_2} seconds')

# Searching Small List: 0.00400090217590332 seconds
# Searching Large List: 0.04300975799560547 seconds

And here are the results for our dictionaries, using the same number of inputs.

import time

dict_1 = {}
for i in range (100000):
    dict_1 [i]= i

start_time = time.time()
value = dict_1[99999]
completed_time = time.time() - start_time
print (f'Searching Dictionary 1: {completed_time} seconds')

dict_2 = {}
for i in range (1000000):
    dict_2 [i]= i

start_time_1 = time.time()
value = dict_2[999999]
completed_time_1 = time.time() - start_time
print (f'Searching Dictionary 2: {completed_time} seconds')

# Searching Dictionary 1: 0.0 seconds
# Searching Dictionary 2: 0.0 seconds

Notice how dictionaries are significantly faster, and how search runtime increases as input increases on our lists. This is because dictionaries in Python are implemented as hash tables, something we listed as a critical difference between these two data types in our previous section.

In a nutshell, hash tables are made up of hash functions, which map data of any length to a fixed-length value (hashes). It doesn’t matter what your input is (10, 1000, or 10000); the result will always be a predetermined, fixed-length hash. Since the same string will always produce an exact hash, they’re incredibly fast to compute, especially compared to lists, as seen in our previous example.

Python Dictionary vs List: When To Use Each

Generally speaking, you’ll want to use a list data structure when your elements need to follow a strictly sequential order or when dealing with data you’ll most likely need to modify later. Dictionaries and lists are both mutable, but your dictionary keys can’t be duplicates, and when you’re dealing with massive amounts of data, there’s also room for massive bugs. However, remember that their search method is reasonably expensive and has a slower runtime.

 On the other hand, dictionaries are better for any type of data that doesn’t need to be stored and accessed through an ordered sequential index. In every other aspect, dictionaries are superior to lists in terms of runtime and overall efficiency. Their most popular methods (search, append and delete) are inexpensive and faster to execute, thanks to how Python implemented them.

Dan Aveledo
Bachelor of Business Administration. Specialized in SEO, web development, and digital marketing during the last decade. Currently discovering the endless possibilities that coding offers. In my spare time, you'll find me lifting weights and creating tools that make my life easier.