Key Difference Between List
Key Difference Between List
👉Mutability:
List: Mutable (modifiable).
Tuple: Immutable (non-modifiable).
Set: Mutable, but elements must be immutable.
Dictionary: Mutable; keys are immutable, but values can change.
👉Order:
List: Maintains order of elements.
Tuple: Maintains order of elements.
Set: No guaranteed order.
Dictionary: As of Python 3.7+, insertion order is preserved.
👉Uniqueness:
List: Allows duplicates.
Tuple: Allows duplicates.
Set: Only unique elements.
Dictionary: Unique keys, values can be duplicated.
👉Data Structure:
List: Ordered collection.
Tuple: Ordered collection.
Set: Unordered collection.
Dictionary: Collection of key-value pairs
Let us know more about Lists, Tuples, Sets and Dictionaries in following topics:
👉List: The Versatile Collection
Definition: Lists are ordered collections of items that can be of different types. They are mutable,
meaning their elements can be changed after the list is created.
Syntax: Created with square brackets [].
Features:
Index-based: You can access elements by their position in the list.
Allows duplicate elements.
Elements can be added, removed, or changed.
Use Cases: When you need an ordered collection of items that may need to be modified, or when you
want to store a sequence of items.
Syntax & Examples:
list1 = [3 , 4, 'ABC', 3, 'list']
list2 = []
list3 = list((4, 2, 8))
print(list1)
print(list2)
print(list3)
#OUTPUT:
[3, 4, 'ABC', 3, 'list']
[]
[4, 2, 8]
Indexing
list1 = [1, 2, "mrcoder", 3]
print(list1[2])
#OUTPUT
mrcoder
Adding New Element
list1 = ["1", "2", "3"]
list1.append("4")
print(list1)
#OUTPUT
['1', '2', '3', '4']
Deleting Element
list1 = ["1", "2", "3", "4"]
list1.pop()
print(list1)
#OUTPUT
['1', '2', '3']
Sorting Elements
list1 = [6, 34, 24, 1, 234]
list1.sort()
print(list1)
#output
[1, 6, 24, 34, 234]
Searching Elements
list1 = [34, 323, 74, 132, 11]
# index() returns index for 4 in list1
print(list1.index(11))
#OUTPUT
4
Reversing Elements
list1 = [34, 323, 74, 132, 11]
list1.reverse()
print(list1)
#OUTPUT
[11, 132, 74, 323, 34]
Counting Elements
list1 = [1, 6, 3, 6, 8, 1, 5]
print(list1.count(6))
#OUTPUT
2
👉Tuple: The Immutable Collection
Definition: Tuples are similar to lists but are immutable, meaning once a tuple is created, its elements
cannot be changed.
Syntax: Created with parentheses ().
Features:
Index-based.
Allows duplicate elements.
Cannot be modified after creation (immutable).
Use Cases: When you need an ordered collection of items that should not change through the course of
the program. Ideal for storing fixed data.
Syntax & Examples:
tuple1 = (1, 2, 'abc', 3, 'def')
tuple2 = ()
tuple3 = tuple((1, 2, 3))
print(tuple1)
print(tuple2)
print(tuple3)
#OUTPUT
(1, 2, 'abc', 3, 'def')
()
(1, 2, 3)
Indexing
tuple1 = (6, 2, "mrcoder", 7)
print(tuple1[2])
#OUTPUT
mrcoder
👉Set: The Unique Element Collector
Definition: Sets are unordered collections of unique elements. They are mutable and do not allow
duplicate elements.
Syntax: Created with curly braces {} or the set() function for an empty set.
Features:
Unordered, so elements cannot be accessed by index.
Automatically remove duplicate elements.
Elements can be added or removed.
Use Cases: When you need to ensure all elements are unique or when you need to perform set
operations like union, intersection, difference, etc.
Syntax & Examples:
thisset = {"apple", "banana", "cherry"}
print(thisset)
# Note: the set list is unordered, meaning: the items will appear in a random order.
#OUTPUT
{'banana', 'apple', 'cherry'}
👉Dictionary: Key-Value Pairing
Definition: Dictionaries are unordered collections of key-value pairs. Keys must be unique and immutable,
but values can be of any type and mutable.
Syntax: Created with curly braces {} with key-value pairs separated by colons :.
Features:
Key-value pairs allow direct access to values by keys.
Keys must be unique and immutable (e.g., strings, numbers, or tuples).
Values can be of any type and can be changed.
Elements can be added, removed, or changed.
Use Cases: When you need to associate keys with values, like looking up values by some identifier. Ideal
for mappings or storing data in a way that makes it easily retrievable by its name or identifier.
In Python versions < 3.7: is an unordered collection of data.
In Python v3.1: a new type of dictionary called ‘OrderedDict’ was introduced, which was similar to
dictionary in python; the difference was that orderedDict was ordered (as the name suggests)
In the latest version of Python, i.e. 3.7: Finally, in python 3.7, dictionary is now an ordered
collection of key-value pairs. The order is now guaranteed in the insertion order, i.e. the order in
which they were inserted.
Syntax & Examples:
dict1 = {"key1": "value1", "key2": "value2"}
dict2 = {}
dict3 = dict({1: "one", 2: "two"})
print(dict1)
print(dict2)
print(dict3)#OUTPUT
{'key1': 'value1', 'key2': 'value2'}
{}
{1: 'one', 2: 'two'}
Indexing
dict1 = {"one": 1, "two": 2, "three": 3}
print(dict1.keys())
print(dict1.values())
print(dict1['two'])
#OUTPUT
dict_keys(['one', 'two', 'three'])
dict_values([1, 2, 3])
2
Adding New Element
dict1 = {"India": "IN", "United States": "USA", "Algeria": "DZ"}
dict1.update({"Aruba": "AW"})
print(dict1)
dict1.pop("Algeria")
print(dict1)
#OUTPUT
{'India': 'IN', 'United States': 'USA', 'Algeria': 'DZ', 'Aruba': 'AW'}
{'India': 'IN', 'United States': 'USA', 'Aruba': 'AW'}
Deleting Element
dict1 = {"India": "IN", "United States": "USA", "Algeria": "DZ"}
dict1.pop('Algeria')
print(dict1)
#OUTPUT
{'India': 'IN', 'United States': 'USA'}
Sorting Elements
dict1 = {"India": "IN", "United States": "USA", "Algeria": "DZ"}
print(sorted(dict1))
#OUTPUT
['Algeria', 'India', 'United States']
Searching Elements
dict1 = {"India": "IN", "United States": "USA", "Algeria": "DZ"}
print(dict1['Algeria'])
#OUTPUT
DZ
NOTE: An unordered collection lacks a data structure that maintains the order in which the data was
added. An ordered collection, on the other hand, has a data structure that does.
A dictionary (in Python v3.6 and earlier) may appear ordered, but it is not; sets, on the other hand,
are an unordered collection. While it does save the keys that have been added to it, accessing via
the key is still possible, but not at a precise integer index.
In a dictionary, every key is distinct and serves as an index via which you can get values. However,
a dictionary’s key storage is not kept in the order that they are entered, making it unordered.
Python 3.1’s “OrderedDict” and Python 3.7’s Dictionary, on the other hand, are ordered
collections of key-value data since they preserve the insertion order.
👉Key Differences Between Dictionary, List, Set, and Tuple
👉Syntax
Dictionary: Key-value pairs are enclosed in curly brackets {} and separated by commas.
List: Uses square brackets [] to denote entries separated by commas.
Set: Comma-separated elements using curly brackets { }.
Tuple: Uses parenthesis() to divide components with commas.
👉Order
Dictionary: In Python 3.7+, it keeps order; in Python 3.6, it is unordered.
List: Maintains order.
Set: Not arranged.
Tuple: Maintains order.
👉Duplicate Data
Dictionary: Keys are unique, values can be duplicated.
List: Allows duplicate elements.
Set: Does not allow duplicate elements.
Tuple: Allows duplicate elements.
👉Indexing
Dictionary: Key-based indexing.
List: Integer-based indexing starting from 0.
Set: No index-based mechanism.
Tuple: Integer-based indexing starting from 0.
👉Adding Elements
Dictionary: Uses key-value pairs.
List: New items can be added using append() method.
Set: Uses add() method.
Tuple: Being immutable, new data cannot be added.
👉Deleting Elements
Dictionary: Uses pop(key) method to remove specified key and value.
List: Uses pop() method to delete an element.
Set: Uses pop() method to remove an element.
Tuple: Being immutable, no data can be popped or deleted.
👉Sorting Elements
Dictionary: Keys can be sorted using the sorted() method.
List: Uses sort() method to sort elements.
Set: Unordered, so sorting is not applicable.
Tuple: Being immutable, data cannot be sorted.
👉Searching Elements
Dictionary: Uses the get(key) method to retrieve value for a specified key.
List: Uses index() method to search and return index of first occurrence.
Set: Unordered, so searching is not applicable.
Tuple: Uses index() method to search and return index of first occurrence.
👉Reversing Elements
Dictionary: No integer-based indexing, so no reversal.
List: Uses reverse() method to reverse elements.
Set: Unordered, so reversing is not advised.
Tuple: Being immutable, reverse method is not applicable.
👉Counting Elements
Dictionary: count() not defined for dictionaries.
List: Uses count() method to count occurrence of a specific element.
Set: count() is not defined for sets.
Tuple: Uses count() method to count occurrence of a specific element.
print(dict2)
print(dict3)
Output:
{'key2': 'value2', 'key1': 'value1'}
{}
{1: 'one', 2: 'two', 3: 'three'}
Indexing
Code:
dict1 = {"one": 1, "two": 2, "three": 3}
print(dict1.keys())
print(dict1.values())
print(dict1['two'])
Output:
['three', 'two', 'one']
[3, 2, 1]
2
Adding New Element
Code:
dict1 = {"India": "IN", "Russia": "RU", "Australia": "AU"}
dict1.update({"Canada": "CA"})
print(dict1)
dict1.pop("Australia")
print(dict1)
Output:
{'Canada': 'CA', 'Australia': 'AU', 'India': 'IN', 'Russia': 'RU'}
{'Canada': 'CA', 'India': 'IN', 'Russia': 'RU'}
Deleting Element
Code:
dict1 = {"India": "IN", "Russia": "RU", "Australia": "AU"}
dict1.pop('Russia')
print(dict1)
Output:
{'Australia': 'AU', 'India': 'IN'}
Sorting Elements
Code:
dict1 = {"India": "IN", "Russia": "RU", "Australia": "AU"}
print(sorted(dict1))
Output:
['Australia', 'India', 'Russia']
Searching Elements
Code:
dict1 = {"India": "IN", "Russia": "RU", "Australia": "AU"}
print(dict1['Australia'])
Output:
AU
If you’re questioning if both orderedDict and dict are ordered in python 3.7. Then why are there two
implementations? Is there any difference?
We can leave that for when we talk about dictionaries in detail. But until then, we should know what
dictionaries are, and their purpose, as that is something that will never change.
Collection VS Features Mutable Ordered Indexing Duplicate Data
List ✔ ✔ ✔ ✔
Tuple 𐄂 ✔ ✔ ✔
Set ✔ 𐄂 𐄂 𐄂
Dictionary ✔ ✔ ✔ 𐄂
NOTE: An ordered collection is when the data structure retains the order in which the data was added,
whereas such order is not retained by the data structure in an unordered collection.
Sets, on one hand, are an unordered collection, whereas a dictionary (in python v3.6 and before)
on the other may seem ordered, but it is not. It does retain the keys added to it, but at the same
time, accessibility at a specific integer index is not possible; instead, accessibility via the key is
possible.
Each key is unique in a dictionary and acts as an index as you can access values using it. But the
order in which keys are stored in a dictionary is not maintained, hence unordered. Whereas
python 3.7’s Dictionary and ‘OrderedDict’ introduced in python 3.1 are ordered collections of key-
value data as they maintain the insertion order.
Let’s dig deeper into the differences between these collections :
Key Differences Between Dictionary, List, Set, and Tuple
Syntax
Dictionary: Uses curly brackets { } with key-value pairs separated by commas.
List: Employs square brackets [ ] with comma-separated elements.
Set: Utilizes curly brackets { } with comma-separated elements.
Tuple: Employs parentheses ( ) with comma-separated elements.
Order
Dictionary: Maintains order in Python 3.7+ but is unordered in Python 3.6.
List: Maintains order.
Set: Unordered.
Tuple: Maintains order.
Duplicate Data
Dictionary: Keys are unique, values can be duplicated.
List: Allows duplicate elements.
Set: Does not allow duplicate elements.
Tuple: Allows duplicate elements.
Indexing
Dictionary: Key-based indexing.
List: Integer-based indexing starting from 0.
Set: No index-based mechanism.
Tuple: Integer-based indexing starting from 0.
Adding Elements
Dictionary: Uses key-value pairs.
List: New items can be added using append() method.
Set: Uses add() method.
Tuple: Being immutable, new data cannot be added.
Deleting Elements
Dictionary: Uses pop(key) method to remove specified key and value.
List: Uses pop() method to delete an element.
Set: Uses pop() method to remove an element.
Tuple: Being immutable, no data can be popped or deleted.
Sorting Elements
Dictionary: Keys can be sorted using the sorted() method.
List: Uses sort() method to sort elements.
Set: Unordered, so sorting is not applicable.
Tuple: Being immutable, data cannot be sorted.
Searching Elements
Dictionary: Uses the get(key) method to retrieve value for a specified key.
List: Uses index() method to search and return index of first occurrence.
Set: Unordered, so searching is not applicable.
Tuple: Uses index() method to search and return index of first occurrence.
Reversing Elements
Dictionary: No integer-based indexing, so no reversal.
List: Uses reverse() method to reverse elements.
Set: Unordered, so reversing is not advised.
Tuple: Being immutable, reverse method is not applicable.
Counting Elements
Dictionary: count() not defined for dictionaries.
List: Uses count() method to count occurrence of a specific element.
Set: count() is not defined for sets.
Tuple: Uses count() method to count occurrence of a specific element.
Quiz Pop
Quiz Type
SCQ
100
Success Rate:35%
Which data structure allows duplicate elements?
List
Tuple
Set
Dictionary
Submit
Quiz Pop
Quiz Type
SCQ
100
Success Rate:35%
In Python 3.7, what method can be used to add a new key-value pair to a dictionary?
push()
append()
update()
add()
Submit
Conclusion
Lists and Tuples vary in mutability as lists are mutable, whereas tuples are not.
Set is the only unordered collection in python 3.7.
Dictionaries store data in the form of key-value pairs in python and remain a controversy when it
comes to whether they’re ordered or unordered. As this varies with multiple versions of python.
Python v<=3.6 has dictionaries as unordered, but at the same time, orderedDict was introduced in
python 3.1, and then finally python 3.7 has both orderedDict and Dictionary and now both are
ordered.
Hope this information gives more clarity on what are the differences between list, tuple, set and
dictionary in python. And what use cases do they serve and hope it gives you clarity on when to use which
collection.