Difference Between List vs Dictionary in Python: A Complete Guide
--
Which data structure are you planning to use for your Python application? Let’s go through a comparison of Python lists and dictionaries.
Lists are ordered Python data structures in which every element can be identified by an index. Dictionaries are data structures in which each element is a key-value pair. Your choice between lists or dictionaries depends on the requirements you have for your Python application.
There are many data types in Python. Lists and dictionaries are two common ones and in this article, we will go through a comparison between the two so you know when to use one or the other.
Let’s discover lists and dictionaries!
What is the Difference Between List and Dictionary in Python?
Let’s start with simple and concise definitions of lists and dictionaries so you can have a quick idea of what they are.
Lists are collections of ordered elements that can be of multiple types. Lists are also mutable and iterable. You can use an index to access the elements in a list and the index value goes from 0 to n-1 where n is the number of elements in the list.
To create a Python list you use square brackets. List items are enclosed in square brackets and are comma separated.
Below you can see an example of a list that has three elements of different types (float, string, and integer):
values = [4.5, 'hour', 23]
Here are the main features of lists:
- Ordered: a list maintains the order of its elements. This can be an important requirement in the logic of your application.
- Indexed: you can access the elements in a list by using an integer index that goes from 0 to n-1 (where n is the number of elements in the list).
- Mutable: you can modify the elements in a list after creating the list.
- Iterable: using a Python loop you can go through all the elements of a list. This can be extremely useful when you want to apply a specific logic to all the elements in a list.