GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Python Technologies
  • Databases
  • Computer Programming
  • Web Development
  • Java Technologies
  • Computer Science
  • Mobile Development
  • Big Data & Analytics
  • Microsoft Technologies
  • DevOps
  • Latest Technologies
  • Machine Learning
  • Digital Marketing
  • Software Quality

This view

  • Original page
  • New address

GeezerVison is showing www.tutorialspoint.com — Python Collections Module

Python Tutorial
  • Python - Home
  • Python - Overview
  • Python - History
  • Python - Features
  • Python vs C++
  • Python - Hello World Program
  • Python - Application Areas
  • Python - Interpreter
  • Python - Environment Setup
  • Python - Virtual Environment
  • Python - Basic Syntax
  • Python - Variables
  • Python - Private Variables
  • Python - Data Types
  • Python - Type Casting
  • Python - Unicode System
  • Python - Literals
  • Python - Operators
  • Python - Arithmetic Operators
  • Python - Comparison Operators
  • Python - Assignment Operators
  • Python - Logical Operators
  • Python - Bitwise Operators
  • Python - Membership Operators
  • Python - Identity Operators
  • Python - Walrus Operator
  • Python - Operator Precedence
  • Python - Comments
  • Python - User Input
  • Python - Numbers
  • Python - Booleans
  • Python - Floating Points
  • Python - Control Flow
  • Python - Decision Making
  • Python - If Statement
  • Python - If else
  • Python - Nested If
  • Python - Conditional User Inputs
  • Python - Match-Case Statement
  • Python - Loops
  • Python - for Loops
  • Python - for-else Loops
  • Python - While Loops
  • Python - break Statement
  • Python - continue Statement
  • Python - pass Statement
  • Python - Nested Loops
  • Python Functions & Modules
  • Python - Functions
  • Python - Default Arguments
  • Python - Keyword Arguments
  • Python - Keyword-Only Arguments
  • Python - Positional Arguments
  • Python - Positional-Only Arguments
  • Python - Arbitrary Arguments
  • Python - Variables Scope
  • Python - Function Annotations
  • Python - Modules
  • Python - Packing and Unpacking
  • Python - Built in Functions
  • Python Strings
  • Python - Strings
  • Python - Slicing Strings
  • Python - Modify Strings
  • Python - String Concatenation
  • Python - String Formatting
  • Python - Escape Characters
  • Python - String Methods
  • Python - String Exercises
  • Python Lists
  • Python - Lists
  • Python - Access List Items
  • Python - Change List Items
  • Python - Add List Items
  • Python - Remove List Items
  • Python - Loop Lists
  • Python - List Comprehension
  • Python - Sort Lists
  • Python - Copy Lists
  • Python - Join Lists
  • Python - List Methods
  • Python - List Exercises
  • Python Tuples
  • Python - Tuples
  • Python - Access Tuple Items
  • Python - Update Tuples
  • Python - Unpack Tuples
  • Python - Loop Tuples
  • Python - Join Tuples
  • Python - Tuple Methods
  • Python - Namedtuple
  • Python - Tuple Exercises
  • Python Sets
  • Python - Sets
  • Python - Access Set Items
  • Python - Add Set Items
  • Python - Remove Set Items
  • Python - Loop Sets
  • Python - Join Sets
  • Python - Copy Sets
  • Python - Set Operators
  • Python - Set Methods
  • Python - Set Exercises
  • Python Dictionaries
  • Python - Dictionaries
  • Python - Access Dictionary Items
  • Python - Change Dictionary Items
  • Python - Add Dictionary Items
  • Python - Remove Dictionary Items
  • Python - Dictionary View Objects
  • Python - Loop Dictionaries
  • Python - Copy Dictionaries
  • Python - Nested Dictionaries
  • Python - Dictionary Methods
  • Python - Dictionary Exercises
  • Python Arrays
  • Python - Arrays
  • Python - Access Array Items
  • Python - Add Array Items
  • Python - Remove Array Items
  • Python - Loop Arrays
  • Python - Copy Arrays
  • Python - Reverse Arrays
  • Python - Sort Arrays
  • Python - Join Arrays
  • Python - Array Methods
  • Python - Array Exercises
  • Python File Handling
  • Python - File Handling
  • Python - Write to File
  • Python - Read Files
  • Python - Renaming and Deleting Files
  • Python - Directories
  • Python - File Methods
  • Python - OS File/Directory Methods
  • Python - OS Path Methods
  • Object Oriented Programming
  • Python - OOPs Concepts
  • Python - Classes & Objects
  • Python - Class Attributes
  • Python - Class Methods
  • Python - Static Methods
  • Python - Constructors
  • Python - Access Modifiers
  • Python - Inheritance
  • Python - Multiple Inheritance
  • Python - Multilevel Inheritance
  • Python - Polymorphism
  • Python - Method Overriding
  • Python - Method Overloading
  • Python - Dynamic Binding
  • Python - Dynamic Typing
  • Python - Abstraction
  • Python - Encapsulation
  • Python - Interfaces
  • Python - Packages
  • Python - Inner Classes
  • Python - Anonymous Class and Objects
  • Python - Singleton Class
  • Python - Wrapper Classes
  • Python - Enums
  • Python - Reflection
  • Python - Data Classes
  • Python Errors & Exceptions
  • Python - Syntax Errors
  • Python - Exceptions
  • Python - try-except Block
  • Python - try-finally Block
  • Python - Raising Exceptions
  • Python - Exception Chaining
  • Python - Nested try Block
  • Python - User-defined Exception
  • Python - Logging
  • Python - Assertions
  • Python - Warnings
  • Python - Built-in Exceptions
  • Python - Debugger (PDB)
  • Python Multithreading
  • Python - Multithreading
  • Python - Thread Life Cycle
  • Python - Creating a Thread
  • Python - Starting a Thread
  • Python - Joining Threads
  • Python - Naming Thread
  • Python - Thread Scheduling
  • Python - Thread Pools
  • Python - Main Thread
  • Python - Thread Priority
  • Python - Daemon Threads
  • Python - Synchronizing Threads
  • Python Synchronization
  • Python - Inter-thread Communication
  • Python - Thread Deadlock
  • Python - Interrupting a Thread
  • Python Networking
  • Python - Networking
  • Python - Socket Programming
  • Python - URL Processing
  • Python - Generics
  • Python Libraries
  • NumPy Tutorial
  • Pandas Tutorial
  • SciPy Tutorial
  • Matplotlib Tutorial
  • Django Tutorial
  • OpenCV Tutorial
  • Python Miscellenous
  • Python - Date & Time
  • Python - Maths
  • Python - Iterators
  • Python - Generators
  • Python - Generator Expressions
  • Python - Lambda Expressions
  • Python - Closures
  • Python - Decorators
  • Python - Recursion
  • Python - Reg Expressions
  • Python - PIP
  • Python - Database Access
  • Python - Weak References
  • Python - Serialization
  • Python - Templating
  • Python - Output Formatting
  • Python - Performance Measurement
  • Python - Data Compression
  • Python - CGI Programming
  • Python - XML Processing
  • Python - GUI Programming
  • Python - Command-Line Arguments
  • Python - Docstrings
  • Python - JSON
  • Python - Sending Email
  • Python - Further Extensions
  • Python - Tools/Utilities
  • Python - Odds and Ends
  • Python - GUIs
  • Python Advanced Concepts
  • Python - Abstract Base Classes
  • Python - Custom Exceptions
  • Python - Higher Order Functions
  • Python - Object Internals
  • Python - Memory Management
  • Python - Metaclasses
  • Python - Metaprogramming with Metaclasses
  • Python - Mocking and Stubbing
  • Python - Monkey Patching
  • Python - Signal Handling
  • Python - Type Hints
  • Python - Automation Tutorial
  • Python - Humanize Package
  • Python - Context Managers
  • Python - Coroutines
  • Python - Descriptors
  • Python - Diagnosing and Fixing Memory Leaks
  • Python - Immutable Data Structures
  • Python - Domain Specific Language (DSL)
  • Python - Data Model
  • Python Useful Resources
  • Python - Questions & Answers
  • Python - Interview Questions & Answers
  • Python - Online Quiz
  • Python - Quick Guide
  • Python - Reference
  • Python - Cheatsheet
  • Python - Projects
  • Python - Useful Resources
  • Python - Discussion
  • Python Compiler
  • NumPy Compiler
  • Matplotlib Compiler
  • SciPy Compiler
Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Online Resume Builder
  • HR Interview Questions
  • Computer Glossary
  • Who is Who

Python Collections Module



Previous
Quiz
Next

The Python collections contains different type of containers. The container is an object which holds different elements and can access the elements and iterate over the object. It contains containers like list, dict, set etc to improve the functionalities of the this containers collections module was introduced.

The collection module provides alternative to the built in data types such as list, tuples, dictionary and sets. It provides additional data structures and operations that are more efficient than the built-in types in certain situations.

Here, in the following table we can find different containers with there functionality −

container functionality

namedtuple

factory function for creating tuple subclasses with named fields

deque

list-like container with fast appends and pops on either end

ChainMap

dict-like class for creating a single view of multiple mappings

Counter

dict subclass for counting hashable objects

OrderedDict

dict subclass that remembers the order entries were added

defaultdict

dict subclass that calls a factory function to supply missing values

UserDict

wrapper around dictionary objects for easier dict subclassing

UserList

wrapper around list objects for easier list subclassing

UserString

wrapper around string objects for easier string subclassing

namedtuple

The namedtuple() in Python is a data type from the collections module. It assigns a name to each position in a tuple, allowing elements to be accessed by field names, similar to how we access elements in a tuple by index.

Syntax

Following is the syntax of the Python namedtuple() data type −

class collections.namedtuple(typename, field_names, rename, default)

Example

Following is the basic example of the Python namedtuple() data type −

from collections import namedtuple
student1 = namedtuple('student1',['name','rollno', 'marks'])
var = student1(name = 'Sai',rollno=237, marks=89)
print("Name :",var.name)
print("Rollno :",var.rollno)
print("Marks :",var.marks)

Following is the output of the above code −

Name : Sai
Rollno : 237
Marks : 89

deque

In Python, deque() is one of the datatypes, which returns a new deque object initialized left-to-right (using append()) with data from iterable. If iterable is not specified, the new deque is empty.

The deque is implemented using collections module. When we need to perform faster operations like append and pop an element we prefer deque as its time complexity is O(1) time as compard to list that provides O(n) time complexity.

Syntax

Following is the syntax of the Python deque() class −

class collections.deque([iterable[, maxlen]])

Example

Following is an basic example of Python deque() class −

from collections import deque
d = deque('xyz')
print(d)

Following is the output of the above code −

deque(['x', 'y', 'z'])

ChainMap

In Python, ChainMap class is used to convert multiple dictionaries or mappings into single unit. If no maps are specified, a single empty dictionary is provided so that a new chain always has at least one mapping.

The ChainMap() class is defined in Collections module. It is often much faster than creating a new dictionary.

Syntax

Following is the syntax of the Python ChainMap() −

collections.ChainMap(iterable1, iterable2, iterable3)

Example

Following is an basic example of the Python ChainMap() −

# Python program to demonstrate 
# ChainMap 	
from collections import ChainMap 	
d1 = {'one': 1, 'two': 2} 
d2 = {'three': 3, 'four': 4} 
d3 = {'five': 5, 'six': 6} 	
# Defining the chainmap 
c = ChainMap(d1, d2, d3) 	
print(c) 

Following is the output of the above code −

ChainMap({'one': 1, 'two': 2}, {'three': 3, 'four': 4}, {'five': 5, 'six': 6})

Counter

Python Counter is a container that hold count of objects. It is used to count items available or exist in iterables. Counts are allowed to be any integer value including zero or negative counts.

Counter is a subclass of the dictionary. It represents data as a key and value. It inherites all the methods and properties of the dictionary. It allows to perform artimetic and set operations. It can be used with any iterable which implements iteration protocol.

Syntax

Following is the syntax of the Python Counter−

class collections.Counter([iterable-or-mapping])

Example

In the following example we have initializated the Counter in different ways −

from collections import Counter
# With sequence of items 
print(Counter(['x','x','z','x','y','z','x','x','z','x']))
# with dictionary
print(Counter({'y':3, 'z':5, 'x':2}))
# with keyword arguments
print(Counter(z=3, x=5, y=2))

Following is the output of the above code −

Counter({'x': 6, 'z': 3, 'y': 1})
Counter({'z': 5, 'y': 3, 'x': 2})
Counter({'x': 5, 'z': 3, 'y': 2})

OrderDict

In Python, OrderedDict is a subclass of dictionary that remembers the order of the keys that were inserted. The only difference between OrderedDict() and the dict() lies in their handling of key order.

The standard dictionary does not guarantee any specific order when iterated whereas, the OrderedDict provides a specific order in which keys are added into the dictionary and maintain the same order when iterated.

Syntax

Following is the syntax of the Python OrderedDict() class −

collections.OrderedDict()

Example

Following is an basic example of the Python OrderedDict() −

# A Python program to demonstrate working of OrderedDict
from collections import OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4

for key, value in od.items():
    print(key,":",value)

Following is the output of the above code −

a : 1
b : 2
c : 3
d : 4

defaultdict

The Python defaultdict() is a container, which is similar to the dictionaries. It is present in the collection module. It is a subclass of the dictionary class which returns a dictionary as object.

The functionality of the both dictionaries and defaultdict are similar, the only difference is the defualtdict does not raise a KeyError. It provides a default value for the key which does not exists.

Syntax

Following is a syntax of the Python defaultdict() class −

defaultdict(default_factory)

Example

Following is an basic example of the Python defaultdict() class −

from collections import defaultdict
def default():
    return 'Key not found'

dic1 = defaultdict(default)
dic1[1] = 'one'
dic1[2] = 'two'
dic1[3] = 'Three'
print(dic1)
print(dic1[5])

Following is the output of the above code −

defaultdict(<function default at 0x000002040ACC8A40>, {1: 'one', 2: 'two', 3: 'Three'})
Key not found

UserDict

The Python Userdict() is a dictionary present in the collections module. It is a class acts as a wrappers around the dictionary objects. This class is useful when one wants to create a dictionary of their own with some modified functionality or with some new functionality.

It can be considered as adding new behaviour to the dictionary. This class takes a dictionary instance as an argument and simulates a dictionary that is kept in a regular dictionary. The dictionary is accessible by the data attribute of this class.

Syntax

Following is the syntax of the Python Userdict()−

collection.Userdict([data])

Example

Following is a basic example of the Python Userdict() class −

from collections import UserDict
dic = {'a':1,'b': 2,'c': 3,'d':4}
# Creating an UserDict
userD = UserDict(dic)
print(userD)

Following is the output of the above code −

{'a': 1, 'b': 2, 'c': 3, 'd': 4}

UserList

The Python UserList is a container like list present in collections module. This class acts as a wrapper class around the list objects. It is useful when one wants to create a list of their own with some modified functionality or with some new functionality. It can be considered as a way of adding new functionality for the list.

The UserList() takes a list instance as an argument and simulates a list that is kept in a regular list. The list is accessible by the data attribute of the this class.

Syntax

Following is the Syntax of the Python UserList class −

collections.UserList(data)

Example

Following is an basic example of the Python UserList() −

# Python program to demonstrate
# userlist
from collections import UserList
List1 = [10, 20, 30, 40]
# Creating a userlist
userlist = UserList(List1)
print(userlist.data)

Following is the output of the above code −

[10, 20, 30, 40]

UserString

The Python UserString is present in collections module. This is a class which acts as a wrapper class around a string. This class is useful to create a string of our own and can also modify the functionally of the methods and can also add new method to the class. It can be considered as a way of adding new behaviors for the string.

The UserString class takes any argument that can be converted to string and simulates a string whose content is kept in a regular string. The string is accessible by the data attribute of this class.

Syntax

Following is the syntax of the Python UserString −

collections.UserString(data)

Example

Following is an basic example of the Python UserString class −

from collections import UserString
data1 = [1,2,3,4]
# Creating an UserDict
user_str = UserString(data1)
print(user_str)
print("type :", type(user_str))

Following is the output of the above code −

[1, 2, 3, 4]
type : <class 'collections.UserString'>
python_modules.htm
Tutorix - AI Tutor
Previous Quiz Next
Advertisements
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.