SlideShare a Scribd company logo
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
 

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

Lecture 8 Library classes
Lecture 8 Library classesLecture 8 Library classes
Lecture 8 Library classes
 
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
 

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

To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsPaul Groth
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Product School
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...Product School
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeCzechDreamin
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Product School
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCzechDreamin
 
The architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdfThe architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdfalexjohnson7307
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomCzechDreamin
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...Product School
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsExpeed Software
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Thierry Lestable
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoTAnalytics
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka DoktorováCzechDreamin
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlPeter Udo Diehl
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaRTTS
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxJennifer Lim
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyJohn Staveley
 

Recently uploaded (20)

To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi IbrahimzadeFree and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
Free and Effective: Making Flows Publicly Accessible, Yumi Ibrahimzade
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya HalderCustom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
Custom Approval Process: A New Perspective, Pavel Hrbacek & Anindya Halder
 
The architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdfThe architecture of Generative AI for enterprises.pdf
The architecture of Generative AI for enterprises.pdf
 
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone KomSalesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
Salesforce Adoption – Metrics, Methods, and Motivation, Antone Kom
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT Professionals
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024IoT Analytics Company Presentation May 2024
IoT Analytics Company Presentation May 2024
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová10 Differences between Sales Cloud and CPQ, Blanka Doktorová
10 Differences between Sales Cloud and CPQ, Blanka Doktorová
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 

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.