What Are Differences Between Lists And Dictionaries In Python?

Differences between lists and dictionaries in python

As a Python developer, you must have worked a lot with lists and dictionaries. So can you tell the differences between lists and dictionaries in Python? Whether the answer is yes or no, you should read this article because you will get a lot of new knowledge!

Differences between lists and dictionaries in python

Here are some basic differences between lists and dictionaries that we would like to clarify for you.

Definition difference

Let’s review the definitions of the two to see how they differ!

List: a data type that allows storing many different data types and accessing the elements inside it through the index of that element in the list. The indexes in list are sorted in ascending order, with 0 as the starting index.

Dictionary: like list, it is also a data type that allows storing many data types. But dictionary doesn’t use the index to access but uses the key. The key of a dictionary is not just a number like a list; it can also be a string or a tuple. And finally, the keys in the dictionary are not sorted in any order.

Based on their definition, we can easily see the difference between them is how they are accessed and how the keys/indexes are arranged. Now, keep reading, and we will clarify these differences in the example in the next section.

Syntax difference

List syntax:

[value1, value2, value3, ...]

Description:

The list is enclosed in square brackets [ ], and its elements are separated by a comma ‘,‘.

Dictionary syntax:

{'key1': value1, 'key2': value2, 'key3': value3, ...}

Description:

The dictionary is enclosed in curly braces { }. Inside are elements in the form of key-value pairs separated by commas ‘,‘.

We can quickly realize the syntax difference between a list and a dictionary by looking at it. 

Now, let’s clarify their definition and syntax differences through a concrete example!

# SYNTAX DIFFERENCE
print("SYNTAX DIFFERENCE")

# Create a list
simpleList = ["learnshareit", "w3schools", "codecademy"]
print("List:\n", simpleList)

# Create a dict
simpleDict = {
    "python": "learnshareit",
    "js": "w3schools",
    "java": "codecademy",
}
print("Dictionary:\n", simpleDict)

# DEFINITION DIFFERENCE
print("\n\nDEFINITION DIFFERENCE")

# Access a list
print("This is simpleList[0]:", simpleList[0])

# Access a dict
print("This is simpleDict['python']:", simpleDict["python"])

# Order of indexes
print("\nIndexes in List are sorted in ascending:")
for i, v in list(enumerate(simpleList)):
    print(f"Index: {i}")

# Order of keys
print("Keys in Dictionary are unordered:")
for key in simpleDict.keys():
    print(f"Key: {key}")

Output:

SYNTAX DIFFERENCE
List:
['learnshareit', 'w3schools', 'codecademy']
Dictionary:
{'python': 'learnshareit', 'js': 'w3schools', 'java': 'codecademy'}


DEFINITION DIFFERENCE
This is simpleList[0]: learnshareit
This is simpleDict['python']: learnshareit

Indexes in List are sorted in ascending:
Index: 0
Index: 1
Index: 2
Keys in Dictionary are unordered:
Key: python
Key: js
Key: java

Execution speed difference

To measure the difference in execution time between the dictionary and the list, we use the time() function in the time module.

time() syntax:

time.time()

Description:

This function returns the number of seconds since the epoch.

Below is an example showing the difference in execution time between the dictionary and the list. Let’s code and see which has better speed!

import time

simpleList = ['learnshareit', 'w3schools', 'codecademy']
simpleDict = {
    'python': 'learnshareit',
    'js': 'w3schools',
    'java': 'codecademy',
}

# Get the start time
start = time.time()

# Access the element of List 1 million times
for i in range(1000000):
    a = simpleList[0]

# Get the end time
end = time.time()

# Get the elapsed time
elapsed_time = end - start
print('List execution speed:', elapsed_time, 'seconds')

# Get the start time
start = time.time()

# Access the element of Dict 1 million times
for i in range(1000000):
    b = simpleDict['python']

# Get the end time
end = time.time()

# Get the elapsed time
elapsed_time = end - start
print('Dictionary execution speed:', elapsed_time, 'seconds')

Output:

List execution speed: 0.08394908905029297 seconds
Dictionary execution speed: 0.1009368896484375 seconds

As you can see, the list’s access speed is relatively faster than the dictionary’s access speed.

Summary

As we said, this article has brought you a lot of new knowledge, right? If you know something else about the differences between lists and dictionaries in Python, let us know in the comment section below.

Have a nice day!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *