Collections
In Python, the collections module is part of the standard library and provides specialized container datatypes that extend the functionality of built-in containers like dict, list, set, and tuple. Below are the main classes and their use cases:
There are four collection data types in the Python programming language:
- List is a collection which is ordered and changeable. Allows duplicate members.
- Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
- Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
- Dictionary is a collection which is ordered** and changeable. No duplicate members.
Mutable : In programming, mutable refers to an object or data type that can be modified or changed after it is created. Eg. Array, list
Immutable : when an object or data type that can't be modified or changed after it is created is called immutable. int, float, char
- Lists: Lists are used to store multiple items in a single variable.
- List can contain duplicate items.
- List in Python are Mutable. Hence, we can modify, replace or delete the items.
- List are ordered. It maintain the order of elements based on how they are added.
- Accessing items in List can be done directly using their position (index), starting from 0.
· You can create a list using square brackets [] or the list() constructor.
fruits = ["apple", "banana", "cherry"]
# Using square bracketsmy_list = [1, 2, 3, 4, 5]# Using list()another_list = list(("Palak", "Methi", "Tomato")) # Notice the double parentheses# Lists can contain different data typesmixed_list = [1, "hello", 3.14, True]More details on List - Tuples: A tuple is a collection which is ordered and immutable and allow duplicate values.
- Tuples are used to store multiple items in a single variable.
- Tuples are written with round brackets.
coordinates = (10, 20)
- Sets: A set is a collection which is unordered,unique collection, unchangeable*, and unindexed.
Sets are used to store multiple items in a single variable.
Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage.
unique_numbers = {1, 2, 3}thisset = {"apple", "banana", "cherry"}
print(thisset)
- Dictionaries: Key-value pairs.
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and do not allow duplicates.
Dictionaries are written with curly brackets, and have keys and values:
student = {"name": "John", "age": 20}
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Counter
- Purpose: Counts the occurrences of elements in an iterable.
- Usage:
from collections import Counter
data = ['a', 'b', 'c', 'a', 'b', 'b']
counter = Counter(data)
print(counter) # Output: Counter({'b': 3, 'a': 2, 'c': 1})
print(counter.most_common(1)) # Output: [('b', 3)]
6. Input and Output
- Input: Get data from the user.
name = input("Enter your name: ")- Output: Print data to the console.
print(f"Hello, {name}!")More Details on Input Output7. Comments
- Used for documentation and are ignored by the interpreter.
# This is a single-line comment."""This is a multi-line comment.Useful for longer explanations."""8. Error Handling
- Manage errors using
try-exceptblocks.
try: result = 10 / 0except ZeroDivisionError: print("Cannot divide by zero.")9. Modules and Libraries
- Python includes a rich set of libraries for various tasks.
import mathprint(math.sqrt(16))10. File Handling
- Reading and writing files.
with open("example.txt", "w") as file: file.write("Hello, Python!")Example: Combining Building Blocks
# Program to calculate the factorial of a numberdef factorial(n): if n == 0 or n == 1: return 1 else: return n * factorial(n - 1)try: num = int(input("Enter a number: ")) if num < 0: print("Factorial is not defined for negative numbers.") else: print(f"The factorial of {num} is {factorial(num)}")except ValueError: print("Please enter a valid number.")
These building blocks provide the foundation for creating complex and powerful Python applications.
Keywords : Keywords in Python are reserved words that have predefined meanings and purposes. They cannot be used as variable names, function names, or identifiers. Python keywords are case-sensitive and written in lowercase, except for True, False, and None.
List of Python Keywords
Here is the list of all keywords in Python 3:
True | Boolean value, the opposite of False. |
and | Logical AND operator. |
as | Used for aliasing imports. |
assert | For debugging; tests a condition. |
async | Defines asynchronous functions. |
await | Waits for the result of an async call. |
break | Exits a loop prematurely. |
class | Defines a class. |
continue | Skips the rest of the loop iteration. |
def | Defines a function. |
del | Deletes an object. |
elif | Else if condition in control structures. |
else | Defines the alternative block. |
except | Handles exceptions. |
finally | Executes code after try-except. |
for | Loop construct. |
from | Used in imports. |
global | Declares a global variable. |
if | Conditional statement. |
import | Imports modules. |
in | Membership operator or loop construct. |
is | Tests object identity. |
lambda | Defines an anonymous function. |
nonlocal | Declares a non-local variable. |
not | Logical NOT operator. |
or | Logical OR operator. |
pass | Acts as a placeholder. |
raise | Raises an exception. |
return | Returns a value from a function. |
try | Defines a block to test for errors. |
while | Loop construct. |
with | Simplifies exception handling. |
yield | Pauses and resumes a generator function. |
Key Points
1. Keywords cannot be used as identifiers.
2. They are essential for defining the structure and behavior of Python programs.
Python's simplicity ensures that the keyword set is small and meaningful.
No comments:
Post a Comment