Differences and Applications of List, Tuple, Set and Dictionary in Python
Last Updated :
04 Sep, 2024
Python provides us with several in-built data structures such as lists, tuples, sets, and dictionaries that store and organize the data efficiently. In this article, we will learn the difference between them and their applications in Python.
Difference between List, Tuple, Set, and Dictionary
The following table shows the difference between various Python built-in data structures.
List | Tuple | Set | Dictionary |
---|
A list is a non-homogeneous data structure that stores the elements in columns of a single row or multiple rows.
| A Tuple is a non-homogeneous data structure that stores elements in columns of a single row or multiple rows.
| The set data structure is non-homogeneous but stores the elements in a single row.
| A dictionary is also a non-homogeneous data structure that stores key-value pairs.
|
The list can be represented by [ ]
| A tuple can be represented by ( )
| The set can be represented by { }
| The dictionary can be represented by { }
|
The list allows duplicate elements
| Tuple allows duplicate elements
| The Set will not allow duplicate elements
| The dictionary doesn’t allow duplicate keys.
|
The list can be nested among all
| A tuple can be nested among all
| The set can be nested among all
| The dictionary can be nested among all
|
Example: [1, 2, 3, 4, 5]
| Example: (1, 2, 3, 4, 5)
| Example: {1, 2, 3, 4, 5}
| Example: {1: “a”, 2: “b”, 3: “c”, 4: “d”, 5: “e”}
|
A list can be created using the list() function
| Tuple can be created using the tuple() function.
| A set can be created using the set() function
| A dictionary can be created using the dict() function.
|
A list is mutable i.e we can make any changes in the list.
| A tuple is immutable i.e we can not make any changes in the tuple.
| A set is mutable i.e we can make any changes in the set, its elements are not duplicated.
| A dictionary is mutable, its Keys are not duplicated.
|
List is ordered
| Tuple is ordered
| Set is unordered
| Dictionary is ordered (Python 3.7 and above)
|
Creating an empty list
l=[]
| Creating an empty Tuple
t=()
| Creating a set
a=set() b=set(a)
| Creating an empty dictionary
d={}
|
Python List
Python Lists are just like dynamic-sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python.
Applications of Python List
Here are five important applications of Python lists:
1. Data Storage and Manipulation
- Application: Python lists are used to store and manipulate collections of data, whether homogeneous (e.g., all integers) or heterogeneous (e.g., a mix of integers, strings, and other types).
- Example: A list can store a series of sensor readings, user inputs, or any other sequential data that can be modified, updated, or analyzed.
Python
data = [23, 45, 12, 67, 34]
data.append(89) # Add an item
data.remove(45) # Remove an item
2. Implementing Stacks and Queues
- Application: Lists are commonly used to implement stacks (LIFO: Last-In, First-Out) and queues (FIFO: First-In, First-Out) due to their ability to add and remove elements from the end or beginning.
- Example: Using
append()
to push onto a stack and pop()
to remove the top element.
Python
stack = []
stack.append('a') # Push onto stack
stack.append('b')
print(stack.pop()) # Pop from stack -> 'b'
3. Iteration and Data Processing
- Application: Lists are ideal for storing data that needs to be iterated over and processed, such as reading data from files, performing computations, or generating reports.
- Example: Iterating through a list of numbers to calculate their sum.
Python
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(f"Total: {total}")
4. Dynamic Arrays
- Application: Lists in Python are dynamic arrays, meaning they can grow and shrink in size. This is useful in applications where the size of the dataset isn’t known in advance and needs to be adjusted dynamically.
- Example: Collecting user inputs or dynamically generating a list of results based on computations.
Python
results = []
for i in range(10):
results.append(i * i)
5. Storing and Processing Strings
- Application: Lists are often used to store and manipulate strings, especially when dealing with text processing tasks such as tokenization, filtering, or transforming data.
- Example: Splitting a sentence into words and performing operations on each word.
Python
sentence = "Python lists are powerful"
words = sentence.split()
for word in words:
print(word.upper())
Python Tuple
A Tuple is a collection of Python objects separated by commas. In some ways, a tuple is similar to a list in terms of indexing, nested objects, and repetition but a tuple is immutable, unlike lists that are mutable.
Applications of Python Tuple
Here are five important applications of Python tuples:
1. Immutable Data Storage
- Purpose: Tuples are immutable, meaning once created, they cannot be modified. This makes them ideal for storing data that should not change throughout the program, such as configuration settings, constants, or fixed data points.
- Example: Storing the coordinates of a point
(x, y)
in a 2D space.
Python
2. Dictionary Keys
- Purpose: Because tuples are immutable, they can be used as keys in a dictionary. This is not possible with lists, as they are mutable and hence unhashable.
- Example: Using tuples to represent composite keys in a dictionary.
Python
locations = {
("Paris", "France"): "Eiffel Tower",
("New York", "USA"): "Statue of Liberty"
}
3. Storing Heterogeneous Data
- Purpose: Tuples can hold elements of different data types. This makes them useful for grouping together heterogeneous data that logically belongs together.
- Example: Storing a person’s name, age, and email in a single tuple.
Python
person = ("John Doe", 30, "johndoe@example.com")
Python Set
A Python Set is an unordered collection data type that is iterable, mutable and has no duplicate elements. Python’s set class represents the mathematical notion of a set.
Applications of Python Set
Here are five important applications of Python sets:
1. Removing Duplicates from a Set
- Application: When you need to eliminate duplicate elements from a list, converting the list to a set is a quick and efficient way to do so.
- Example:
Python
my_list = [1, 2, 2, 3, 4, 4, 5]
unique_elements = set(my_list)
print(unique_elements)
# Output: {1, 2, 3, 4, 5}
2. Set Operations (Union, Intersection, Difference)
- Application: Sets are ideal for performing mathematical operations like union, intersection, and difference, which are useful in fields like data analysis, database management, and computational biology.
- Example:
Python
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
union = set1.union(set2) # {1, 2, 3, 4, 5, 6}
intersection = set1.intersection(set2) # {3, 4}
difference = set1.difference(set2) # {1, 2}
3. Membership Testing
- Application: Checking for the existence of an element in a collection is very efficient with sets due to their underlying hash table implementation. This makes sets a good choice for membership testing in scenarios like checking if an item is in a list of prohibited items.
- Example:
Python
prohibited_items = {"knife", "gun", "drugs"}
item = "knife"
if item in prohibited_items:
print(f"{item} is prohibited.")
4. Finding Common Elements
- Application: Sets are highly efficient for finding common elements between two or more collections. This is useful in scenarios like finding common interests, mutual friends, or common values between datasets.
- Example:
Python
friends_A = {"Alice", "Bob", "Charlie"}
friends_B = {"Bob", "David", "Eve"}
common_friends = friends_A.intersection(friends_B)
print(common_friends) # Output: {'Bob'}
5. Handling Data in Multi-Set Scenarios
- Application: Sets are useful when dealing with multiple data sources where you need to ensure the uniqueness of the combined dataset or identify overlaps between different data sources.
- Example:
Python
dataset1 = {"apple", "banana", "cherry"}
dataset2 = {"banana", "cherry", "date"}
# {'apple', 'banana', 'cherry', 'date'}
combined_unique = dataset1.union(dataset2)
# {'banana', 'cherry'}
overlap = dataset1.intersection(dataset2)
Python Dictionary
Dictionary in Python is an ordered (since Py 3.7) [unordered (Py 3.6 & prior)] collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized.
Applications of Python Dictionary
Here are five important applications of Python dictionaries:
1. Database Record Representation
- Application: Dictionaries are often used to represent database records where each key-value pair corresponds to a column and its associated value. This makes it easy to access and manipulate data based on field names.
- Example:
Python
record = {
'id': 1,
'name': 'John Doe',
'email': 'john.doe@example.com',
'age': 30
}
2. Counting Frequency of Elements
- Application: Dictionaries can be used to count the frequency of elements in a list, string, or any iterable. The element itself serves as the key, and its frequency is the value.
- Example:
Python
elements = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
frequency = {}
for item in elements:
frequency[item] = frequency.get(item, 0) + 1
# Output: {'apple': 3, 'banana': 2, 'orange': 1}
3. Fast Lookup Tables
- Application: Dictionaries provide O(1) average time complexity for lookups, making them ideal for creating fast lookup tables. This can be used in applications like caching, memoization, or mapping operations.
- Example
Python
lookup = {
'USD': 'United States Dollar',
'EUR': 'Euro',
'JPY': 'Japanese Yen'
}
currency_name = lookup.get('USD')
# Output: 'United States Dollar'
4. Storing and Accessing JSON Data
- Application: JSON data, which is commonly used for APIs and web services, maps directly to Python dictionaries. This allows for easy storage, access, and manipulation of JSON data.
- Example:
Python
import json
json_data = '{"name": "Alice", "age": 25, "city": "New York"}'
data = json.loads(json_data)
# Accessing data
name = data['name']
# Output: 'Alice'
5. Grouping Data by Keys
- Application: Dictionaries can be used to group data by certain keys, which is particularly useful in data analysis and aggregation tasks.
- Example:
Python
data = [
{'name': 'Alice', 'department': 'HR'},
{'name': 'Bob', 'department': 'IT'},
{'name': 'Charlie', 'department': 'HR'},
{'name': 'David', 'department': 'IT'}
]
grouped = {}
for item in data:
department = item['department']
if department not in grouped:
grouped[department] = []
grouped[department].append(item['name'])
# Output: {'HR': ['Alice', 'Charlie'], 'IT': ['Bob', 'David']}
Differences and Applications of List, Tuple, Set and Dictionary in Python – FAQs
What Are the Differences Between Lists, Tuples, Sets, and Dictionaries in Python?
Lists:
- Syntax:
[]
- Ordered: Yes (Maintains the insertion order)
- Mutable: Yes (Elements can be changed)
- Duplicates: Yes (Allows duplicate elements)
- Example:
[1, 2, 3, 4]
Tuples:
- Syntax:
()
- Ordered: Yes (Maintains the insertion order)
- Mutable: No (Elements cannot be changed once assigned)
- Duplicates: Yes (Allows duplicate elements)
- Example:
(1, 2, 3, 4)
Sets:
- Syntax:
{}
or set()
- Ordered: No (No guarantee of order in Python versions before 3.7)
- Mutable: Yes (Elements can be added or removed)
- Duplicates: No (Does not allow duplicate elements)
- Example:
{1, 2, 3, 4}
Dictionaries:
- Syntax:
{key: value}
- Ordered: Yes (Maintains the insertion order starting from Python 3.7)
- Mutable: Yes (Keys and values can be changed)
- Duplicates: No (Keys must be unique, but values can be duplicated)
- Example:
{'a': 1, 'b': 2, 'c': 3}
When Should You Use a List Over a Tuple in Python?
Use a List When:
- You need a collection of items that may need to be modified (e.g., adding, removing, or changing items).
- The collection is likely to change during the program’s execution.
- You need to perform operations that require mutability.
Use a Tuple When:
- You need an immutable collection of items (e.g., representing fixed records or configurations).
- The collection should not be changed after its creation, which can help prevent accidental modification.
- You want to use the collection as a dictionary key or in sets, where immutability is required.
How Does a Set Differ from a List and Tuple in Python?
Order:
- Sets: Do not guarantee order (no index-based access).
- Lists/Tuples: Maintain order and support index-based access.
Duplicates:
- Sets: Do not allow duplicate elements.
- Lists/Tuples: Allow duplicate elements.
Operations:
- Sets: Provide set operations like union, intersection, and difference.
- Lists/Tuples: Do not support these operations directly.
What Are the Common Use Cases for Dictionaries in Python?
1. Key-Value Pair Storage: Storing data where each item has a unique identifier (key) and an associated value.
student_scores = {‘Alice’: 85, ‘Bob’: 90}
2. Lookup Tables: Efficiently mapping and retrieving values based on a key.
phone_book = {‘John’: ‘123-4567’, ‘Jane’: ‘987-6543’}
3. Counting Frequencies: Using keys to count occurrences of items.
from collections import Counter items = [‘apple’, ‘banana’, ‘apple’] frequency = Counter(items)
4. Configuration Settings: Storing configuration options in a structured way.
config = {‘theme’: ‘dark’, ‘language’: ‘en’}
How Do List Comprehensions Work in Python?
List comprehensions provide a concise way to create lists. They consist of an expression followed by a for
loop inside square brackets.
Syntax:
[expression for item in iterable if condition]
Example:
1. Basic List Comprehension:
squares = [x**2 for x in range(10)] # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
2. With a Condition:
even_squares = [x**2 for x in range(10) if x % 2 == 0] # Output: [0, 4, 16, 36, 64]
3. Nested List Comprehension:
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flattened = [num for row in matrix for num in row] # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Similar Reads
Differences and Applications of List, Tuple, Set and Dictionary in Python
Python provides us with several in-built data structures such as lists, tuples, sets, and dictionaries that store and organize the data efficiently. In this article, we will learn the difference between them and their applications in Python. Table of Content Difference between List, Tuple, Set, and
11 min read
Difference between List and Dictionary in Python
Lists and Dictionaries in Python are inbuilt data structures that are used to store data. Lists are linear in nature whereas dictionaries stored the data in key-value pairs. In this article, we will see the difference between the two and find out the time complexities and space complexities which ar
8 min read
Difference between Json and Dictionary in Python
In Python, dictionaries and JSON (JavaScript Object Notation) both facilitate structured data representation, yet they diverge in usage and syntax. In this article, we will discuss the Definition of JSON and Dictionary and the difference between JSON and Dictionary in Python. JSON vs DictionaryDicti
4 min read
Difference Between List and Tuple in Python
Lists and Tuples in Python are two different implementations of array data structure. List is Mutable and Tuple is not (Cannot update an element, insert and delete elements)Tuples are faster because of read only nature. Memory can be efficiently allocated and used for tuples.Differences between List
6 min read
Difference Between Del, Remove and Pop in Python Lists
del is a keyword and remove(), and pop() are in-built methods in Python. The purpose of these three is the same but the behavior is different. remove() method deletes values or objects from the list using value and del and pop() deletes values or objects from the list using an index. del Statementde
2 min read
Difference between List and Array in Python
In Python, lists and arrays are the data structures that are used to store multiple items. They both support the indexing of elements to access them, slicing, and iterating over the elements. In this article, we will see the difference between the two. Operations Difference in Lists and ArraysAccess
6 min read
Python Memory Consumption: Dictionary VS List of Tuples
In this article, we are going to see memory consumption in dictionaries and a list of tuples. Memory Consumption by dict vs list of tuples Dictionary occupies much more space than a list of tuples. Even an empty dict occupies much space as compared to a list of tuples. Example 1: As we can clearly s
4 min read
Ways to create a dictionary of Lists - Python
A dictionary of lists is a type of dictionary where each value is a list. These dictionaries are commonly used when we need to associate multiple values with a single key. Initialize a Dictionary of ListsThis method involves manually defining a dictionary where each key is explicitly assigned a list
3 min read
Ways to create a dictionary of Lists - Python
A dictionary of lists is a type of dictionary where each value is a list. These dictionaries are commonly used when we need to associate multiple values with a single key. Initialize a Dictionary of ListsThis method involves manually defining a dictionary where each key is explicitly assigned a list
3 min read
Store Functions in List and Call in Python
In Python, a list of functions can be created by defining the tasks and then adding them to a list. Here’s a simple example to illustrate how to do this: [GFGTABS] Python def say_hello(): return "Hello!" #Store a function "say_hello" in a list greetings = [say_hello] #Call the fi
3 min read
Differences between Array and Dictionary Data Structure
Arrays:The array is a collection of the same type of elements at contiguous memory locations under the same name. It is easier to access the element in the case of an array. The size is the key issue in the case of an array which must be known in advance so as to store the elements in it. Insertion
5 min read
Python | Convert two lists into a dictionary
Interconversion between data types is usually necessary for real-time applications as certain systems have certain modules that require input in a particular data type. Let's discuss a simple yet useful utility of conversion of two lists into a key: value pair dictionary in Python. Converting Two Li
11 min read
Create a List of Tuples in Python
List of tuple is used to store multiple tuples together into List. We can create a list that contains tuples as elements. This practice is useful for memory efficiency and data security as tuples are immutable. The simplest way to create a list of tuples is to define it manually by specifying the va
4 min read
Difference Between List and Set in C#
The list is C# is the same as the list in JAVA. Basically, it is a type of object which can store variables. But in difference with objects, it stores the variables only in a specific order. Following is the syntax from which we can declare variables: Syntax: List<int> numbers = new List<in
2 min read
Difference between Append, Extend and Insert in Python
In Python, append(), extend() and insert() are list methods used to add elements to a list. Each method has different behaviors and is used in different scenarios. AppendThe append() method adds a single element which can be string, integer, tuple or another list to the end of the list. If we pass a
3 min read
Difference between Append, Extend and Insert in Python
In Python, append(), extend() and insert() are list methods used to add elements to a list. Each method has different behaviors and is used in different scenarios. AppendThe append() method adds a single element which can be string, integer, tuple or another list to the end of the list. If we pass a
3 min read
Iterate through list of dictionaries in Python
In this article, we will learn how to iterate through a list of dictionaries. List of dictionaries in use: [{'Python': 'Machine Learning', 'R': 'Machine learning'}, {'Python': 'Web development', 'Java Script': 'Web Development', 'HTML': 'Web Development'}, {'C++': 'Game Development', 'Python': 'Game
3 min read
Internal implementation of Data Structures in Python
Python provides a variety of built-in data structures, each with its own characteristics and internal implementations optimized for specific use cases. In this article we are going to discuss about the most commonly used Data structures in Python and a brief overview of their internal implementation
3 min read
How to Take a Tuple as an Input in Python?
Tuples are immutable data structures in Python making them ideal for storing fixed collections of items. In many situations, you may need to take a tuple as input from the user. Let's explore different methods to input tuples in Python. The simplest way to take a tuple as input is by using the split
3 min read