Differences and Applications of List, Tuple, Set and Dictionary in Python (original) (raw)
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. Here are five important applications of Python lists:
1. Data Storage and Manipulation
Lists are great for holding collections of data, whether all of the same type (like all integers) or mixed types (e.g., integers, strings). You can **add, **remove, and **update elements easily.
**Example:
Python `
a = [23, 45, 12, 67, 34] a.append(89) a.remove(45) print(a)
`
Output
[23, 12, 67, 34, 89]
2. Implementing Stacks and Queues
Lists can simulate stack (LIFO) and queue (FIFO) behaviors. Stack operations use append() and pop(), while queues may require **pop(0) or **collections.deque.
**Example:
Python `
s = [] s.append('a') s.append('b') print(s.pop())
`
Explanation: This behaves like a stack. Items are pushed using append(), and the last item ‘b**‘ is popped from the stack.
3. Iteration and Data Processing
Lists are iterable and perfect for processing data, especially in loops where you perform calculations or transformations.
**Example:
Python `
a = [1, 2, 3, 4, 5] t = sum(a) print(f"Total: {t}")
`
**Explanation: We use Python’s built-in **sum() to add all numbers in the list and print the total.
4. Dynamic Arrays
Lists can grow or shrink in size, which is useful when collecting data dynamically such as user inputs or computation results.
**Example:
Python `
s = [] for i in range(10): s.append(i * i) print(s)
`
Output
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
**Explanation: We create a list of squares from 0 to 9 dynamically using a loop and store the results in the list.
5. Storing and Processing Strings
Lists can be used to manipulate strings for tasks like tokenization, filtering, or formatting.
**Example:
Python `
s = "Subtle art of not giving a bug" w = s.split() for word in w: print(word.upper())
`
Output
SUBTLE ART OF NOT GIVING A BUG
**Explanation: We split a sentence into words using split() and convert each word to uppercase using a loop.
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.
1. Immutable Data Storage
Tuples are used when data should not be changed, such as coordinates or constants.
**Example:
Python `
p= (10, 20) print(p)
`
2. Dictionary Keys
Tuples are hashable and can be used as dictionary keys, unlike lists.
**Example:
Python `
p = { ("Paris", "France"): "Eiffel Tower", ("New York", "USA"): "Statue of Liberty" } print(p[("Paris", "France")])
`
3. Storing Heterogeneous Data
Tuples are ideal for grouping data of different types like user records.
**Example:
Python `
p = ("Prajjwal", 22, "prajwal@gfg.org") print(p)
`
Output
('Prajjwal', 22, 'prajwal@gfg.org')
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.
1. Removing Duplicates from a Set
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 `
a = [1, 2, 2, 3, 4, 4, 5] u = set(a) print(u)
`
2. Set Operations
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 `
a = {1, 2, 3, 4} b = {3, 4, 5, 6} print("Union:", a | b) print("Intersection:", a & b) print("Difference:", a - b)
`
Output
Union: {1, 2, 3, 4, 5, 6} Intersection: {3, 4} Difference: {1, 2}
**Explanation: We perform **union (|), **intersection (&), and **difference (-) between two sets.
3. Membership Testing
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 `
ban = {"knife", "gun", "drugs"} i = "knife" if i in ban: print(f"{i} is prohibited.")
`
Output
knife is prohibited.
**Explanation: We check if a given item is in the banned set. Membership testing in sets is fast.
4. Finding Common Elements
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 `
a_f = {"Aryan", "Anurag", "Vishakshi"} b_f = {"Prajjwal", "Brijkant","Aryan", "Kareena"} comm = a_f & b_f print(comm)
`
**Explanation: We use intersection (&) to find common friends between two sets.
5. Handling Data in Multi-Set Scenarios
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 `
d1 = {"apple", "banana", "cherry"} d2 = {"banana", "cherry", "date"} comb = d1 | d2 over = d1 & d2 print("Combined:", comb) print("Overlap:", over)
`
Output
Combined: {'apple', 'cherry', 'banana', 'date'} Overlap: {'cherry', 'banana'}
**Explanation: We merge two sets using union (|) and find shared items using **intersection (&).
Python Dictionary
Dictionary in Python is an ordered (since Py 3.7) 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. Dictionaries store data in key: value pairs. They are ideal for fast lookups and representing structured data. Here are five important applications of Python dictionaries:
1. Database Record Representation
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 `
rec = { 'id': 1, 'name': 'Prajjwal', 'email': 'prajjwal@example.com', 'age': 30 } print(rec['name'])
`
2. Counting Frequency of Elements
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 `
i = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'] freq = {} for item in i: freq[item] = freq.get(item, 0) + 1 print(freq)
`
Output
{'apple': 3, 'banana': 2, 'orange': 1}
**Explanation: We use a dictionary to count how often each fruit appears in the list.
3. Fast Lookup Tables
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' } print(lookup.get('USD'))
`
Output
United States Dollar
4. Storing and Accessing JSON Data
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
a = '{"name": "prajjwal", "age": 23, "city": "Prayagraj"}' data = json.loads(a)
print(data['name'])
`
**Explanation: We parse a JSON string into a Python dictionary and access a value by key.
5. Grouping Data by Keys
Dictionaries can be used to group data by certain keys, which is particularly useful in data analysis and aggregation tasks.
**Example:
Python `
emp = [ {'name': 'prajj', 'dept': 'HR'}, {'name': 'brij', 'dept': 'IT'}, {'name': 'kareena', 'dept': 'HR'}, {'name': 'aryan', 'dept': 'IT'} ]
grp = {} for emp in emp: dept = emp['dept'] grp.setdefault(dept, []).append(emp['name'])
print(grp)
`
Output
{'HR': ['prajj', 'kareena'], 'IT': ['brij', 'aryan']}