Open In App

Differences and Applications of List, Tuple, Set and Dictionary in Python

Last Updated : 04 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

ListTupleSetDictionary

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
point = (10, 20)

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]



Next Article

Similar Reads

three90RightbarBannerImg
  翻译: