Difference Between List Set Tuple Dictionary Python

In Python, the data structures known as List, Set, Tuple, and Dictionary are extensively utilized. These structures are essential for managing and organizing information effectively. To write Python code that is both efficient and impactful, it is important to understand the fundamental distinctions among these data structures.

What is a List?

In Python, a list serves as a built-in data structure that facilitates the storage of numerous items within a single variable. Lists are among the most commonly utilized data structures in Python due to their mutability, ordered nature, and capacity to contain various types of elements.

Lists provide a versatile approach to managing groups of data and include numerous helpful built-in functions. Typically, lists are created by placing the collection of items, separated by commas, within square brackets .

Characteristics of a List

Several characteristics of List in Python are as follows:

  • Ordered: Elements are stored in a particular order, and their position (index) is significant.
  • Mutable: One can modify the elements of a list once it's created (e.g., using append , insert , remove, pop ).
  • Allows Duplicates: There can be several instances of the same element in a list. This means that the element can be repeated n times.
  • Indexed Access: Elements are accessed by their index (which is generally an integer); the index of the first element is 0.
  • Python List Example

Let us see an example of a list in Python.

Example

Example

# simple python program to create a list

# creating a list

lst_1 = [12, 'Example', 3.61, True]

# printing the list

print("List :", lst_1)

# printing its data type

print(type(lst_1))

Output:

Output

List : [12, 'Example', 3.61, True]

<class 'list'>

Explanation:

In this instance, we have generated a list by placing various elements of distinct data types within square brackets .

What is a Set?

A set is defined as an unordered collection of items. This indicates that elements within a set do not follow a specific sequence. Sets are designed to contain only unique elements; they inherently remove any duplicate values that may occur within the collection.

Sets are denoted by curly braces {}, with individual elements within the set being divided by commas. Typically, the set function is utilized to create an empty set, whereas {} is employed to establish an empty dictionary.

Characteristics of a Set

Several characteristics of a set in Python are as follows:

  • Unordered: Elements in a set do not have any particular order.
  • Mutable : Elements can be added or removed from a set after its creation (e.g., with add , remove , discard ).
  • No Duplicates: Sets have unique elements; duplicates are simply ignored (if present).
  • Python Set Example

Below is a straightforward illustration of a set implemented in Python.

Example

Example

#creating the first set

first_set = set(("Example", 14, (1, 2, 3)))

#printing the first set

print(first_set)

#creating the second set

second_set = set("Example")

#printing the second

print(second_set)

Output:

Output

{'Example', (1, 2, 3), 14}

{'n', 't', 'i', 'T', 'o', 'c', 'p', 'e', 'h'}

Explanation:

In this instance, we have formed a set by placing multiple elements within curly braces {}.

What is a Tuple?

A tuple is a fundamental data structure in Python designed for the purpose of holding a collection of objects. It shares similarities with a list regarding indexing, nesting, and the ability to contain repeated elements. However, one key distinction is that tuples are immutable, which implies that their elements cannot be modified after they have been established. To create a tuple, one must enclose the items, which are separated by commas, within parentheses .

Characteristics of a Tuple

Several characteristics of a Tuple in Python are as follows:

  • Ordered: Items are stored in a definite order.
  • Immutable: Once a tuple is made, its items cannot be altered (no addition, deletion, or modification).
  • Supports Duplicates: A tuple may have more than one occurrence of the same element. It means that an element can be present n times.
  • Indexed Access: Access to elements is possible using their indexes, and the index starts with 0.
  • Used Usually with Fixed Collections : Tuples are used to represent collections of records that need not be changed in the future, e.g., coordinates or records.
  • Slightly Smaller than Lists: As tuples are immutable, they occupy less memory than lists.
  • Python Tuple Example

Let us now examine an illustration of a tuple in Python.

Example

Example

# simple python program to create a tuple

# creating a tuple

tpl_1 = (19, 'Python', 7.8, True)

# printing the tuple

print("Tuple :", tpl_1)

# printing type of list

print(type(tpl_1))

Output:

Output

Tuple : (19, 'Python', 7.8, True)

<class 'tuple'>

Explanation:

In this instance, we have formed a set by placing various elements of distinct data types within curly braces {}.

What is a Dictionary?

In Python, a Dictionary is a fundamental data structure utilized for storing data in pairs formatted as 'key: value'. This collection is unordered (although from Python 3.7 onwards, it maintains the order of insertion), mutable, and indexed, with each key being distinct and corresponding to its respective value. Typically, dictionaries are employed to hold related information, such as details pertinent to a specific object or entity, allowing for straightforward retrieval based on the key.

Characteristics of a Dictionary

Several chacteristics of a dictionary in Python are as follows:

  • Unordered: Dictionaries do not follow a particular order to store items. However, starting from Python 3.7+ , the Order is maintained when inserting key-value pairs into the dictionary.
  • Mutable: One can add, delete, or change key-value pairs after the dictionary is created.
  • Unique Keys: A dictionary's keys must be distinct (unique). If you attempt to insert a new value with a present key, the value associated with the key will be replaced.
  • Key-Based Access: Elements are accessed by their keys, not by their indices. This feature helps in finding the items based on the key.
  • Python Dictionary Example

Below is a straightforward illustration of a dictionary in Python.

Example

Example

# simple python program to create a dictionary

# creating a dictionary

dict_1 = {'emp_id': 1001, 'name': 'Irfan', 'job_profile': 'Software Developer'}

# printing the dictionary

print("Dictionary :", dict_1)

# printing type of list

print(type(dict_1))

Output:

Output

Dictionary : {'emp_id': 1001, 'name': 'Irfan', 'job_profile': 'Software Developer'}

<class 'dict'>

Explanation:

In this illustration, we have constructed a dictionary that contains several 'key: value' pairs, which are divided by commas and encapsulated within curly braces {}.

Key Differences between List, Set, Tuple, and Dictionary

Below are the essential distinctions among Lists, Sets, Tuples, and Dictionaries in Python:

Feature List Set Tuple Dictionary
Ordered Yes No Yes Yes (since Python 3.7)
Mutable (Container) Yes (elements can be added, removed, or modified) Yes (elements can be added or removed) No (elements cannot be changed after creation) Yes (key-value pairs can be added, removed, or values modified)
Mutable (Elements) Yes (if the elements themselves are mutable) Yes (if the elements themselves are mutable) No (elements themselves cannot be changed if the tuple is immutable) Yes (values can be mutable; keys must be immutable)
Duplicates Allowed Not Allowed (only unique elements are stored) Allowed Not Allowed (keys must be unique; values can be duplicated)
Indexing/Access Yes (integer-based index, starting from 0) No (elements are not ordered and cannot be accessed by index) Yes (integer-based index, starting from 0) Yes (key-based access; values are retrieved using their unique keys)
Hashing Not Hashable (cannot be used as keys in dictionaries or elements in sets) Hashable (if all elements within the set are hashable) Hashable (if all elements within the tuple are hashable) Not directly hashable (but its keys() and items() views can behave like sets for some operations in later Python versions)
Syntax [item1, item2, ...] {item1, item2, ...} (empty set: set()) (item1, item2, ...) (single element tuple: (item1,)) {key1: value1, key2: value2, ...}
Common Methods append(), extend(), insert(), remove(), pop(), index(),count(), sort(), reverse(),clear(), copy() add(), remove(), discard(),pop(), clear(), copy(), union(), intersection(), difference(), symmetric_difference() count(), index() get(), keys(),values(), items(),update(),pop(), popitem(), clear(), copy(),setdefault()
Memory Overhead Generally higher than tuples for the same number of elements due to dynamic resizing capabilities. Can have overhead due to the need for hash table management to ensure uniqueness. Generally lower than lists for the same number of elements due to fixed size. Can have significant overhead due to the storage of both keys and values and the underlying hash table.
Use Cases Ordered collections needing modification, maintaining order of insertion, and variable-length collections. Storing unique items, membership testing, set algebra operations, and removing duplicates. Representing fixed data structures, ensuring data integrity, used as keys in dictionaries (if elements are hashable), and returning multiple values. It maps the key to their values, efficient lookups by key and represents structured or labeled data.

Conclusion

We have gained significant insights into the distinctions among List, Set, Dictionary, and Tuple. The List, Tuple, and Dictionary (introduced in Python version 3.7) maintain an ordered structure, in contrast to the set, which is unordered. Additionally, the List, Set, and Dictionary exhibit mutability. We have thoroughly examined each criterion in depth.

We maintain the belief that there is much more to anticipate; functionalities and goals may evolve with future releases of Python.

Difference between List, Set, Tuple, and Dictionary in Python FAQs

1. When can we use a list instead of a tuple?

A list is suitable when you need a collection of elements that may be modified (including adding, removing, or changing items) or when the sequence of the elements is significant and can change. Conversely, a tuple should be utilized when you require the items to remain unchanged.

2. What is the major benefit of using a set?

The primary advantage of utilizing a set lies in its ability to store only unique elements while providing efficient methods for membership testing. Additionally, operations performed on sets—including union, intersection, and difference—are executed with high efficiency.

3. Are dictionaries ordered in every version of Python?

No, dictionaries do not maintain an order in every version of Python. They are guaranteed to be ordered starting from version 3.7 and onwards.

4. Can any data type be used as a key in a dictionary?

No, the keys in a dictionary must be immutable, which includes types such as strings, numbers (both integers and floats), and tuples. Mutable objects like lists cannot serve as dictionary keys because their hash values might change over time.

5. How do we decide between a list and a set if we want to store a group of items?

When the elements are arranged in a specific sequence and it is necessary to include duplicate entries, employing a list is the appropriate choice. Conversely, if the objective is to maintain only unique elements where the order is irrelevant, and there may be a need to perform set operations, utilizing a set would be more suitable.

Input Required

This code uses input(). Please provide values below: