Key Difference Between List

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 13

Key Difference Between List, Tuple, Set, and Dictionary in Python

👉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.

Differences Between List, Tuple, Set and Dictionary in Python


Overview
Data structures in python provide us with a way of storing and arranging data that is easily accessible and
modifiable. These data structures include collections. Some of the most commonly used built-in
collections are lists, sets, tuples and dictionary.
Introduction
Having a hard time understanding what Lists, tuples, sets and dictionaries are in python? Everyone who
works on python at least once has been confused about the differences between them or when to use
them. Well, say no more, as we'll break down these Data structure collections' differences and
understand them so that we may never forget them!
Let’s take a closer look at what each of these collections are :
Key Difference Between List, Tuple, Set, and Dictionary in Python
Mutability:
 List: Mutable (modifiable).
 Tuple: Immutable (non-modifiable).
 Set: Mutable, but elements inside 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.
Difference Between List VS Tuple VS Set VS Dictionary in Python
Parameters List Tuple Set Dictionary
A set is an
A list is an ordered, A tuple is an ordered, A dictionary is an
unordered
Definition mutable collection of immutable collection of unordered collection of
collection of unique
elements. elements. key-value pairs.
elements.
Syntax Syntax includes Syntax includes curved Syntax includes Syntax includes curly
square brackets [ , ] brackets ( , ) with ‘,’ curly brackets { , } brackets { , } with ‘,’
Parameters List Tuple Set Dictionary
with ‘,’ separated with ‘,’ separated separated key-value
separated data.
data. data. data.
A list can be created
Tuple can be created A set dictionary can A dictionary can be
using the list()
Creation using the tuple() be created using created using the dict()
function or simple
function. the set() function. function.
assignment to [].
An empty set can
Empty Data An empty list can be An empty tuple can be An empty dictionary
be created by s =
Structure created by l = []. created by t = (). can be created by {}.
set().
It is an ordered It is also an ordered It is an unordered Ordered collection in
collection of data. collection of data. collection of data. Python version 3.7,
Order
unordered in Python
Version=3.6.
Keys are unique, but
Duplicate Duplicate data entry Duplicate data entry is All elements are
two different keys CAN
Data is allowed in a List. allowed in a Tuple. unique in a Set.
have the same value.
Has integer based Also has integer based Does NOT have an Has a Key based
Indexing indexing that starts indexing that starts index based indexing i.e. keys
from ‘0’. from ‘0’. mechanism. identify the value.
New items can be Being immutable, new The add() method update() method
Addition added using the data cannot be added to adds an element to updates specific key-
append() method. it. a set. value pair.
Being immutable, no Elements can be pop(key) removes
Pop() method allows
Deletion data can be randomly deleted specified key along with
deleting an element.
popped/deleted. using pop(). its value.
Immutable, so sorting Unordered, so Keys are sorted by
sort() method sorts
Sorting method is not sorting is not using the sorted()
the elements.
applicable. advised. method.
Unordered, so
index() returns index index() returns index of get(key) returns value
Search searching is not
of first occurrence. first occurrence. against specified key.
applicable.
Immutable, so reverse Unordered, so No integer-based
reverse() method
Reversing method is not reverse is not indexing, so no
reverses the list.
applicable. advised. reversal.
count() method
count() method returns count() not defined count() not defined for
Count returns occurrence
occurrence count. for sets. dictionaries.
count.
Let us know more about Lists, Tuples, Sets and Dictionaries in following topics:
List
Lists are one of the most commonly used data structures provided by python; they are a collection of
iterable, mutable and ordered data. They can contain duplicate data.
Certainly! Here are the code snippets extracted and organized with suitable subheadings for each data
structure:
Syntax
Code:
list1 = [1 , 2, 'abc', 3, 'def']
list2 = []
list3 = list((1, 2, 3))
print(list1)
print(list2)
print(list3)
Output:
[1, 2, 'abc', 3, 'def']
[]
[1, 2, 3]
Indexing
Code:
list1 = [1, 2, "hello", 3]
print(list1[2])
Output:
'hello'
Adding New Element
Code:
list1 = ["one", "two", "three"]
list1.append("four")
print(list1)
Output:
['one', 'two', 'three', 'four']
Deleting Element
Code:
list1 = ["one", "two", "three", "four"]
list1.pop()
print(list1)
Output:
['one', 'two', 'three']
Sorting Elements
Code:
list1 = [100, 3, 4, 12, 1]
list1.sort()
print(list1)
Output:
[1, 3, 4, 12, 100]
Searching Elements
Code:
list1 = [100, 3, 4, 12, 1]
# index() returns index for 4 in list1
print(list1.index(4))
Output:
2
Reversing Elements
Code:
list1 = [100, 3, 4, 12, 1]
list1.reverse()
print(list1)
Output:
[1, 12, 4, 3, 100]
Counting Elements
Code:
list1 = [1, 2, 3, 6, 2, 2, 2]
print(list1.count(2))
Output:
4
Tuple
Tuples are similar to lists. This collection also has iterable, ordered, and (can contain) repetitive data, just
like lists. But unlike lists, tuples are immutable.
Syntax
Code:
tuple1 = (1, 2, 'abc', 3, 4)
tuple2 = ()
tuple3 = tuple((1, 3, 5, "hello"))
print(tuple1)
print(tuple2)
print(tuple3)
Output:
(1, 2, 'abc', 3, 4)
()
(1, 2, 3, 'hello')
Indexing
Code:
tuple1 = (1, 2, "hello", 3)
print(tuple1[2])
Output:
'hello'
Set
Set is another data structure that holds a collection of unordered, iterable and mutable data. But it only
contains unique elements.
Certainly! Here are the code snippets for the "Set" section of the table, including the Syntax and
Searching Elements sections:
Syntax
Code:
set1 = {1, 2, 3, 'abc', 6}
print(set1)
Output:
{'abc', 1, 2, 3, 6}
Dictionary
Unlike all other collection types, dictionaries strictly contain key-value pairs.
 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
Code:
dict1 = {"key1": "value1", "key2": "value2"}
dict2 = {}
dict3 = dict({1: "one", 2: "two", 3: "three"})
print(dict1)

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.

You might also like