There are two types of Data types in Python. They are:
- Mutable Data Types
- Immutable Data Types
The classification of Data types is based on whether the contents can be changed or not.
Mutable Data Types
In general, in Python, we define everything as an object.
After the creation of objects, if the objects can be changed that is defined as mutable data types.
Mutable Operations:
- Inserting
- Appending
- Modifying
- Deleting
Types:
The most commonly used mutable data types are as follows:
- Lists
- Sets
- Dictionaries
Lists
- Lists are an ordered collection of items. These are mutable i.e. we can add, remove, or modify elements after lists have been created.
- Representation of lists is with square brackets i.e. []
- The indexing starts with 0.
- If a user wants to add an element to a list the element is added at the end of the list.
Example:
n = [1,2,3,4,5] n.append(6) print(n)
Output:
[1,2,3,4,5,6]
Sets:
- A set is an unordered collection of elements.
- Elements are unique in set i.e. sets don’t allow duplicate elements.
- Representation of sets is curly braces {}.
Example:
n = {1,2,3} n.add(4) n.remove(1) print(n)
Output:
{2,3,4}
Dictionaries:
- Dictionaries are key-value pairs.
- Dictionaries are collections of unordered collections of key-value pairs.
- Each key is associated with a value.
- In a key-value pair, a value can be a number, string, list, or tuple.
- A key is immutable i.e. key cannot be changed.
- Representation of dictionaries is curly braces {}.
Example:
n = {'a' : 1, 'b' : 2, 'c' : 3} n['d'] = 4 print(n)
Output:
{'a' : 1, 'b' : 3, 'c' : 3, 'd' : 4}