SlideShare a Scribd company logo
1 of 14
Download to read offline
Collections in Python - Where
Data Finds Its Perfect Home
Python is a powerful programming language with a vast standard
library. The collections module is one such library that is a part of the
standard library. It provides an alternative to Python’s built-in data
structures such as lists, dictionaries, and tuples.
The collections module contains various container data types such as
deque, OrderedDict, Counter, and defaultdict, etc.
In this guide, we will discuss the collections module and its different
data types in detail.
The collections module in Python provides alternatives to Python’s
built-in data structures. These alternatives are highly optimized for
different use cases and provide additional functionality beyond what is
available in the built-in data structures.
In this guide, we will cover the following Python collection data types:
1. Counter
2. OrderedDict
3. defaultdict
4. deque
5. namedtuple
6. ChainMap
Counter:
The Counter class is a subclass of the dictionary class. It is used to
count the occurrences of elements in an iterable. The Counter object
takes an iterable as an argument and returns a dictionary where the
keys are the elements in the iterable, and the values are the count of
occurrences of those elements.
Here’s an example:
from collections import Counter
my_list = [1, 2, 2, 3, 3, 3]
my_counter = Counter(my_list)
print(my_counter)
Output:
Counter({3: 3, 2: 2, 1: 1})
OrderedDict:
The OrderedDict class is a subclass of the dictionary class. It is used to
create dictionaries that remember the order in which the keys were
inserted. The order of the keys is maintained by a doubly-linked list.
Here’s an example:
from collections import OrderedDict
my_dict = OrderedDict()
my_dict['a'] = 1
my_dict['b'] = 2
my_dict['c'] = 3
print(my_dict)
Output:
OrderedDict([(‘a’, 1), (‘b’, 2), (‘c’, 3)])
defaultdict:
The defaultdict class is a subclass of the dictionary class. It is used to
create dictionaries with default values for keys that do not exist. The
default value is specified using a callable object that takes no
arguments and returns the default value.
Here’s an example:
from collections import defaultdict
my_dict = defaultdict(int)
my_dict['a'] = 1
my_dict['b'] = 2
print(my_dict['a'])
print(my_dict['c'])
Output:
1
0
deque:
The deque class is a subclass of the list class. It is used to create
double-ended queues. Deques are thread-safe and can be used for
multi-threaded applications.
Here’s an example:
from collections import deque
my_deque = deque([1, 2, 3])
my_deque.append(4)
my_deque.appendleft(0)
print(my_deque)
Output:
deque([0, 1, 2, 3, 4])
namedtuple:
The namedtuple class is used to create tuple subclasses with named
fields. Namedtuples are immutable and can be accessed using dot
notation.
Here’s an example:
from collections import namedtuple
Person = namedtuple('Person', ['name', 'age', 'gender'])
person = Person('John', 30, 'Male')
print(person.name)
print(person.age)
print(person.gender)
Output:
John
30
Male
ChainMap:
The ChainMap class is used to combine multiple dictionaries into a
single dictionary. It isused to search for a key in multiple dictionaries
in the order in which they are provided.
Here’s an example:
from collections import ChainMap
dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
combined_dict = ChainMap(dict1, dict2)
print(combined_dict['a'])
print(combined_dict['d'])
Output:
1
4
When to use Python Collections:
Python collections can be used in various scenarios where Python’s
built-in data structures such as lists, dictionaries, and tuples are not
efficient or optimized for the use case.
The collections module provides alternative data structures that are
highly optimized for specific use cases and provide additional
functionality beyond what is available in the built-in data structures.
Here are some scenarios where Python collections can be used:
1. Counting elements in an iterable:
The Counter class provided by the collections module is used to count
the occurrences of elements in an iterable. This can be used in various
scenarios, such as counting the frequency of words in a document,
counting the occurrence of elements in a list, etc.
2. Maintaining order in a dictionary:
The OrderedDict class provided by the collections module is used to
create dictionaries that remember the order in which the keys were
inserted. This can be used in scenarios where the order of the keys in
the dictionary matters, such as creating a configuration file.
3. Default values for missing keys in a dictionary:
The defaultdict class provided by the collections module is used to
create dictionaries with default values for keys that do not exist. This
can be used in scenarios where you need to set a default value for a key
that does not exist in a dictionary.
4. Efficient deque operations:
The deque class provided by the collections module is used to create
double-ended queues. Deques are highly optimized for operations
such as adding and removing elements from the beginning and end of
the queue.
5. Named tuple:
The namedtuple class provided by the collections module is used to
create tuple subclasses with named fields. Namedtuples are
immutable and can be accessed using dot notation. This can be used in
scenarios where you need to define a simple class with immutable
attributes.
6. Combining multiple dictionaries:
The ChainMap class provided by the collections module is used to
combine multiple dictionaries into a single dictionary. It is used to
search for a key in multiple dictionaries in the order in which they are
provided. This can be used in scenarios where you need to search for a
key in multiple dictionaries and return the value from the first
dictionary that contains the key.
In conclusion, Python collections can be used in various scenarios
where the built-in data structures are not efficient or optimized for the
use case.
The collections module provides optimized data structures that are
highly efficient and provide additional functionality beyond what is
available in the built-in data structures.
Conclusion:
In conclusion, the collections module in Python provides efficient and
optimized data structures that can be used for various use cases.
It provides alternatives to Python’s built-in data structures and
provides additional functionality beyond what is available in the
built-in data structures.
The data types provided by the collections module include Counter,
OrderedDict, defaultdict, deque, namedtuple, and ChainMap. These
data types can be used to create efficient and optimized data
structures for various use cases.

More Related Content

Similar to Collections in Python - Where Data Finds Its Perfect Home.pdf

These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2sadhana312471
 
Kripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptx
Kripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptxKripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptx
Kripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptxsg4795
 
Python Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaPython Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaEdureka!
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in PythonMSB Academy
 
pythonlibrariesandmodules-210530042906.docx
pythonlibrariesandmodules-210530042906.docxpythonlibrariesandmodules-210530042906.docx
pythonlibrariesandmodules-210530042906.docxRameshMishra84
 
An Introduction to the C++ Standard Library
An Introduction to the C++ Standard LibraryAn Introduction to the C++ Standard Library
An Introduction to the C++ Standard LibraryJoyjit Choudhury
 
Chapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptxChapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptxjchandrasekhar3
 
James Jesus Bermas on Crash Course on Python
James Jesus Bermas on Crash Course on PythonJames Jesus Bermas on Crash Course on Python
James Jesus Bermas on Crash Course on PythonCP-Union
 
Python Libraries and Modules
Python Libraries and ModulesPython Libraries and Modules
Python Libraries and ModulesRaginiJain21
 
Module 8 : Implementing collections and generics
Module 8 : Implementing collections and genericsModule 8 : Implementing collections and generics
Module 8 : Implementing collections and genericsPrem Kumar Badri
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptxAshwini Raut
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And AnswersH2Kinfosys
 

Similar to Collections in Python - Where Data Finds Its Perfect Home.pdf (20)

These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
 
Kripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptx
Kripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptxKripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptx
Kripanshu MOOC PPT - Kripanshu Shekhar Jha (1).pptx
 
Python Collections Tutorial | Edureka
Python Collections Tutorial | EdurekaPython Collections Tutorial | Edureka
Python Collections Tutorial | Edureka
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
 
pythonlibrariesandmodules-210530042906.docx
pythonlibrariesandmodules-210530042906.docxpythonlibrariesandmodules-210530042906.docx
pythonlibrariesandmodules-210530042906.docx
 
An Introduction to the C++ Standard Library
An Introduction to the C++ Standard LibraryAn Introduction to the C++ Standard Library
An Introduction to the C++ Standard Library
 
Python libraries
Python librariesPython libraries
Python libraries
 
Python with data Sciences
Python with data SciencesPython with data Sciences
Python with data Sciences
 
PYTHON 101.pptx
PYTHON 101.pptxPYTHON 101.pptx
PYTHON 101.pptx
 
Unit 5
Unit 5Unit 5
Unit 5
 
Chapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptxChapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptx
 
James Jesus Bermas on Crash Course on Python
James Jesus Bermas on Crash Course on PythonJames Jesus Bermas on Crash Course on Python
James Jesus Bermas on Crash Course on Python
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Form part1
Form part1Form part1
Form part1
 
Python for Beginners
Python  for BeginnersPython  for Beginners
Python for Beginners
 
Python Libraries and Modules
Python Libraries and ModulesPython Libraries and Modules
Python Libraries and Modules
 
Module 8 : Implementing collections and generics
Module 8 : Implementing collections and genericsModule 8 : Implementing collections and generics
Module 8 : Implementing collections and generics
 
Chapter 16 Dictionaries
Chapter 16 DictionariesChapter 16 Dictionaries
Chapter 16 Dictionaries
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And Answers
 

More from SudhanshiBakre1

Float Data Type in C.pdf
Float Data Type in C.pdfFloat Data Type in C.pdf
Float Data Type in C.pdfSudhanshiBakre1
 
IoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfIoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfSudhanshiBakre1
 
Internet of Things – Contiki.pdf
Internet of Things – Contiki.pdfInternet of Things – Contiki.pdf
Internet of Things – Contiki.pdfSudhanshiBakre1
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdfSudhanshiBakre1
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdfSudhanshiBakre1
 
Types of AI you should know.pdf
Types of AI you should know.pdfTypes of AI you should know.pdf
Types of AI you should know.pdfSudhanshiBakre1
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdfSudhanshiBakre1
 
Top Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfTop Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfSudhanshiBakre1
 
Epic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfEpic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfSudhanshiBakre1
 
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfDjango Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfSudhanshiBakre1
 
Benefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfBenefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfSudhanshiBakre1
 
Epic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfEpic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfSudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfSudhanshiBakre1
 
Semaphore in Java with Example.pdf
Semaphore in Java with Example.pdfSemaphore in Java with Example.pdf
Semaphore in Java with Example.pdfSudhanshiBakre1
 

More from SudhanshiBakre1 (20)

IoT Security.pdf
IoT Security.pdfIoT Security.pdf
IoT Security.pdf
 
Top Java Frameworks.pdf
Top Java Frameworks.pdfTop Java Frameworks.pdf
Top Java Frameworks.pdf
 
Numpy ndarrays.pdf
Numpy ndarrays.pdfNumpy ndarrays.pdf
Numpy ndarrays.pdf
 
Float Data Type in C.pdf
Float Data Type in C.pdfFloat Data Type in C.pdf
Float Data Type in C.pdf
 
IoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdfIoT Hardware – The Backbone of Smart Devices.pdf
IoT Hardware – The Backbone of Smart Devices.pdf
 
Internet of Things – Contiki.pdf
Internet of Things – Contiki.pdfInternet of Things – Contiki.pdf
Internet of Things – Contiki.pdf
 
Java abstract Keyword.pdf
Java abstract Keyword.pdfJava abstract Keyword.pdf
Java abstract Keyword.pdf
 
Node.js with MySQL.pdf
Node.js with MySQL.pdfNode.js with MySQL.pdf
Node.js with MySQL.pdf
 
File Handling in Java.pdf
File Handling in Java.pdfFile Handling in Java.pdf
File Handling in Java.pdf
 
Types of AI you should know.pdf
Types of AI you should know.pdfTypes of AI you should know.pdf
Types of AI you should know.pdf
 
Streams in Node .pdf
Streams in Node .pdfStreams in Node .pdf
Streams in Node .pdf
 
Annotations in Java with Example.pdf
Annotations in Java with Example.pdfAnnotations in Java with Example.pdf
Annotations in Java with Example.pdf
 
RESTful API in Node.pdf
RESTful API in Node.pdfRESTful API in Node.pdf
RESTful API in Node.pdf
 
Top Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdfTop Cryptocurrency Exchanges of 2023.pdf
Top Cryptocurrency Exchanges of 2023.pdf
 
Epic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdfEpic Python Face-Off -Methods vs.pdf
Epic Python Face-Off -Methods vs.pdf
 
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdfDjango Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
Django Tutorial_ Let’s take a deep dive into Django’s web framework.pdf
 
Benefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdfBenefits Of IoT Salesforce.pdf
Benefits Of IoT Salesforce.pdf
 
Epic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdfEpic Python Face-Off -Methods vs. Functions.pdf
Epic Python Face-Off -Methods vs. Functions.pdf
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 
Semaphore in Java with Example.pdf
Semaphore in Java with Example.pdfSemaphore in Java with Example.pdf
Semaphore in Java with Example.pdf
 

Recently uploaded

How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 

Recently uploaded (20)

How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 

Collections in Python - Where Data Finds Its Perfect Home.pdf

  • 1. Collections in Python - Where Data Finds Its Perfect Home Python is a powerful programming language with a vast standard library. The collections module is one such library that is a part of the standard library. It provides an alternative to Python’s built-in data structures such as lists, dictionaries, and tuples. The collections module contains various container data types such as deque, OrderedDict, Counter, and defaultdict, etc. In this guide, we will discuss the collections module and its different data types in detail. The collections module in Python provides alternatives to Python’s built-in data structures. These alternatives are highly optimized for
  • 2. different use cases and provide additional functionality beyond what is available in the built-in data structures. In this guide, we will cover the following Python collection data types: 1. Counter 2. OrderedDict 3. defaultdict 4. deque 5. namedtuple
  • 3. 6. ChainMap Counter: The Counter class is a subclass of the dictionary class. It is used to count the occurrences of elements in an iterable. The Counter object takes an iterable as an argument and returns a dictionary where the keys are the elements in the iterable, and the values are the count of occurrences of those elements. Here’s an example: from collections import Counter my_list = [1, 2, 2, 3, 3, 3] my_counter = Counter(my_list)
  • 4. print(my_counter) Output: Counter({3: 3, 2: 2, 1: 1}) OrderedDict: The OrderedDict class is a subclass of the dictionary class. It is used to create dictionaries that remember the order in which the keys were inserted. The order of the keys is maintained by a doubly-linked list. Here’s an example: from collections import OrderedDict my_dict = OrderedDict() my_dict['a'] = 1 my_dict['b'] = 2
  • 5. my_dict['c'] = 3 print(my_dict) Output: OrderedDict([(‘a’, 1), (‘b’, 2), (‘c’, 3)]) defaultdict: The defaultdict class is a subclass of the dictionary class. It is used to create dictionaries with default values for keys that do not exist. The default value is specified using a callable object that takes no arguments and returns the default value. Here’s an example: from collections import defaultdict
  • 6. my_dict = defaultdict(int) my_dict['a'] = 1 my_dict['b'] = 2 print(my_dict['a']) print(my_dict['c']) Output: 1 0 deque: The deque class is a subclass of the list class. It is used to create double-ended queues. Deques are thread-safe and can be used for multi-threaded applications.
  • 7. Here’s an example: from collections import deque my_deque = deque([1, 2, 3]) my_deque.append(4) my_deque.appendleft(0) print(my_deque) Output: deque([0, 1, 2, 3, 4]) namedtuple:
  • 8. The namedtuple class is used to create tuple subclasses with named fields. Namedtuples are immutable and can be accessed using dot notation. Here’s an example: from collections import namedtuple Person = namedtuple('Person', ['name', 'age', 'gender']) person = Person('John', 30, 'Male') print(person.name) print(person.age) print(person.gender)
  • 9. Output: John 30 Male ChainMap: The ChainMap class is used to combine multiple dictionaries into a single dictionary. It isused to search for a key in multiple dictionaries in the order in which they are provided. Here’s an example: from collections import ChainMap dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4}
  • 10. combined_dict = ChainMap(dict1, dict2) print(combined_dict['a']) print(combined_dict['d']) Output: 1 4 When to use Python Collections: Python collections can be used in various scenarios where Python’s built-in data structures such as lists, dictionaries, and tuples are not efficient or optimized for the use case. The collections module provides alternative data structures that are highly optimized for specific use cases and provide additional functionality beyond what is available in the built-in data structures.
  • 11. Here are some scenarios where Python collections can be used: 1. Counting elements in an iterable: The Counter class provided by the collections module is used to count the occurrences of elements in an iterable. This can be used in various scenarios, such as counting the frequency of words in a document, counting the occurrence of elements in a list, etc. 2. Maintaining order in a dictionary: The OrderedDict class provided by the collections module is used to create dictionaries that remember the order in which the keys were inserted. This can be used in scenarios where the order of the keys in the dictionary matters, such as creating a configuration file. 3. Default values for missing keys in a dictionary: The defaultdict class provided by the collections module is used to create dictionaries with default values for keys that do not exist. This can be used in scenarios where you need to set a default value for a key that does not exist in a dictionary.
  • 12. 4. Efficient deque operations: The deque class provided by the collections module is used to create double-ended queues. Deques are highly optimized for operations such as adding and removing elements from the beginning and end of the queue. 5. Named tuple: The namedtuple class provided by the collections module is used to create tuple subclasses with named fields. Namedtuples are immutable and can be accessed using dot notation. This can be used in scenarios where you need to define a simple class with immutable attributes. 6. Combining multiple dictionaries: The ChainMap class provided by the collections module is used to combine multiple dictionaries into a single dictionary. It is used to search for a key in multiple dictionaries in the order in which they are provided. This can be used in scenarios where you need to search for a
  • 13. key in multiple dictionaries and return the value from the first dictionary that contains the key. In conclusion, Python collections can be used in various scenarios where the built-in data structures are not efficient or optimized for the use case. The collections module provides optimized data structures that are highly efficient and provide additional functionality beyond what is available in the built-in data structures. Conclusion: In conclusion, the collections module in Python provides efficient and optimized data structures that can be used for various use cases. It provides alternatives to Python’s built-in data structures and provides additional functionality beyond what is available in the built-in data structures.
  • 14. The data types provided by the collections module include Counter, OrderedDict, defaultdict, deque, namedtuple, and ChainMap. These data types can be used to create efficient and optimized data structures for various use cases.