In Python, there are four types of collections. While list
and set
primarily contain homogeneous elements, dict
and tuple
contain heterogeneous elements. Homogeneous refers to elements of the same type.
Examples of collections with homogeneous elements include a collection of employees represented by a list
and a collection of unique employees represented by a set
. Similarly, a collection of integers can be stored in a list
, and a collection of unique integers can be stored in a set
.
Based on the requirement, the appropriate type of collection should be used.
List
- A group of homogeneous elements.
- Allows duplicates.
- A
list
can be created by enclosing elements in[]
, for example,[1, 2, 3, 4]
. - An empty
list
can be initialized using[]
orlist()
.
Set
- A group of homogeneous elements.
- No duplicates are allowed in a
set
, even if the same element is added multiple times. - A
set
can be created by enclosing elements in{}
, for example,{1, 2, 3, 4}
. - An empty
set
can be initialized usingset()
. Initializing an empty set using{}
will result in an emptydict
.
Lists and sets can be compared to tables with columns and rows, while dict
and tuple
can be likened to a row within a table.
Lists can hold duplicate values, whereas sets only hold unique values. If you require a row with column names, a dict
is used; otherwise, a tuple
is preferred.
It is essential to delve deeper into all types of collections to gain a better understanding of them.
l = [1, 2, 3, 3, 4, 4]
l
l = []
l
type(l)
l = list()
l
s = {1, 2, 3, 3, 4, 4}
s
type(s)
s = set() # Initializing an empty set
s
s = {} # 's' will be of type dict
type(s)
Hands-On Tasks
- Create a list with duplicate elements and print it.
- Create a set with duplicate elements and observe the output.
Conclusion
In this article, we explored the differences between lists and sets in Python. Understanding the distinctions between these two types of collections is crucial for efficient programming. Practice creating and manipulating lists and sets to solidify your knowledge. If you have any questions or need further clarification, feel free to engage with the community.