Collections In Python
Python collections are data structures that store multiple items of the same or different types. There are four built-in collection types in Python: list, tuple, set and dictionary. Additionally, there is a module called collections that provides more specialized collection types such as Counter, OrderedDict, defaultdict and namedtuple.
Here are some examples of using Python collections:
List: A list is a collection that is ordered and changeable. The Python lists are defined with square brackets.
# Create a list of fruits
fruits = ["apple", "banana", "cherry"]
# Print the list
print(fruits)
# Output: ['apple', 'banana', 'cherry']
Tuple: A tuple is a collection that is ordered and unchangeable. The Python tuples are written with round brackets.
# Create a tuple of colors
colors = ("red", "green", "blue")
# Print the tuple
print(colors)
# Output: ('red', 'green', 'blue')
Set: A set is a collection that is unordered and unindexed. The Python sets are defined with curly braces.
# Create a set of animals
animals = {"cat", "dog", "bird"}
# Print the set
print(animals)
# Output: {'cat', 'dog', 'bird'}
Dictionary: A dictionary is a collection that is unordered, changeable and indexed. The Python dictionaries are defined with curly braces and have keys and values.
# Create a dictionary of students and their grades
students = {"Alice": 90, "Bob": 80, "Charlie": 85}
# Print the dictionary
print(students)
# Output: {'Alice': 90, 'Bob': 80, 'Charlie': 85}
Counter: A Counter is a subclass of dictionary that counts the occurrences of each element in an iterable or a mapping.
from collections import Counter
# Create a Counter from a list of words
words = ["hello", "world", "hello", "python"]
word_count = Counter(words)
# Print the Counter
print(word_count)
# Output: Counter({'hello': 2, 'world': 1, 'python': 1})
OrderedDict: An OrderedDict is a subclass of dictionary that remembers the order of insertion of keys.
from collections import OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
print('Before Deleting')
for key, value in od.items():
print(key, value)
od.pop('a')
od['a'] = 1
print('\nAfter re-inserting')
for key,value in od.items():
print(key,value)
# Output:
Before Deleting
a 1
b 2
c 3
d 4
# After re-inserting:
b 2
c 3
d 4
a 1
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment