In this post, we will discuss the built-in collections in python.
Let us first understand what do we mean by collections?
👉 Collections are nothing but containers used to store data. So basically, when we want to store any data collectively it can be achieved using collections.
Topics Covered
Collections in Python
There are 4 types of built-in collections in python.
- List
- Tuple
- Set
- Dictionary
Let’s understand them in more detail.
List
In python, a list is a collection that is ordered and changeable. They are written with square [] brackets.
Example:
a = [1,2,3,4,5] print(a)
Tuple
In python, a tuple is a collection that is ordered and unchangeable. They are written with round () brackets.
Example:
b = (1,2,3,4,5) print(b)
Set
In python, a set is a collection that is unordered and unindexed. They are written with curly {} brackets.
The set will never contain a duplicate element.
Example:
c = {1,2,3,4,5} print(c)
Dictionary
In python, a dictionary is a collection that is unordered, indexed, and changeable. They are written with curly {} brackets as a key-value pair.
Example:
d = {'a':1,'b':2,'c':3,'d':4,'e':5} print(d)
Collection Module
The collections module provides alternatives to the above mentioned built-in container data types.
namedtuple()
The namedtuple() function returns a tuple-like object with named fields. These field attributes are accessible by index as well as by lookup.
import collections employee = collections.namedtuple('employee', [name, department, salary]) #Creating new object emp1 = employee("Dipendra", IT, 50000) #Getting attribute value by index emp1[0] #this will give Dipendra #Getting attribute value by lookup emp1.salary #this will give 50000
OrderedDict()
The OrderedDict() function is similar to a normal dictionary object in Python. However, it remembers the order of the keys in which they were first inserted.
import collections d1 = collections.OrderedDict() d1['A'] = 1 d1['C'] = 3 d1['B'] = 2 d1['D'] = 4 for k,v in d1.items(): print (k,v)
While reading and printing the collection the item would be returned in the order they were inserted.
A 1 C 3 B 2 D 4
deque()
A deque object support appends and pops from either end of a list
r = collections.deque([1,2,3,4,5])
Know more about collection modules in python.
Summary
Here is a quick summary of collections in python you have learned above.
I hope you got a basic understanding of using collections in python.
⭐Course Recommendations
We recommend these courses if you want to master your python skills and take them to next level.
1️⃣ Complete Python Developer in 2021: Zero to Mastery
2️⃣ Complete Python Mastery
You may check out our ASP.NET Core tutorial and various other posts on C# as well.
PS: If you found this content valuable and want to return the favor, then