Python programming language has four built-in types of collections, namely List
, Set
, Tuple
, and Dictionary
.
List
list
is an ordered sequence of elements that store multiple values inside a single variable.[]
are used to declare it.listName = [value1, value2, ...]
# list declarationstudents = ['Shubham', 'Parth', 'Pratik', 'Shubham']print("List")print(students)# adding value to liststudents.append('Rohan')print("\nAfter adding value to list")print(students)
list
called students
, and initialize it with a few values.list
on the consoleappend()
method to add a new value to the list
.list
on the console again.The output shows that students
contains the value Shubham
twice. Thus, it allows duplicates values.
After creating the list, we can add values. Therefore, it is mutable.
Set
set
stores multiple values inside a single variable.{}
are used to declare it.setName = {value1, value2, ...}
# set declarationstudents = {'Shubham', 'Parth', 'Pratik', 'Shubham'}print("Set")print(students)# adding value to setstudents.add('Rohan')print("\nAfter adding value to Set")print(students)
set
called students
, and initialize it with a few values.set
on the console.add()
method to add a new value to the set
.set
on the console again.The output shows that students
contains the value Shubham
only once, even though we added it twice. This shows that it doesn’t allow duplicate values.
After creating the set, we can add values. Therefore, it is mutable.The set does not maintain insertion order; it is unordered.
Tuple
tuple
stores multiple values inside a single variable.()
to declare it.tupleName = (value1, value2, ...)
# tuple declarationstudents = ('Shubham', 'Parth', 'Pratik', 'Shubham')print("Tuple")print(students)
tuple
called students
, and initialize it with a few values.tuple
on the consoleThe output shows that students
contains the value Shubham
twice. Therefore, it allows duplicate values.
After creating the tuple, we cannot add or remove any values. Thus, it is immutable.
Dictionary
dictionary
stores data in the form of key-value pairs.{}
are used to declare it.dictionaryName = {
key1: value1,
key2: value2,
...
}
# dictionary declarationstudents = {'student1' : 'Shubham','student2' : 'Parth','student3' : 'Pratik','student1' : 'Shubham',}print('Dictionary')print(students)# add key-value pair to dictionarystudents['student5'] = 'Rohan'print('\nDictionary after adding new key-value pair')print(students)
dictionary
called students
and initialize it with a few key-value pairs.dictionary
on the console.dictionary
.dictionary
on the console again.In the output, students
contains the key-value pair ‘Shubham’ only once, even though we added it twice. Therefore, it doesn’t allow duplicate values.
After creating the dictionary
, we can add more values. Thus, it is mutable.