range:
The range data type in Python is used to generate a sequence of numbers. It is commonly used in for loops for iterating a fixed number of times.
- It does not produce a list, but rather a special iterable object.
Syntax:
range(start, stop, step)- start – starting number (default is 0)
- stop – end (exclusive)
- step – difference between each number (default is 1)
Example:
for i in range(0, 10, 2):
print(i)
#output
0
2
4
6
8Convert to list:
print(list(range(5))) # Output: [0, 1, 2, 3, 4]Dictionary (dict):
A dictionary in Python is a collection of key-value pairs. It allows fast access to data by keys, not by index.
Dictionaries are unordered (as of Python <3.7) and mutable, meaning you can add, update, or delete key-value pairs.
- Defined using curly braces {} with colon : separating keys and values.
1.) Creating a Dictionary:
student = {"name": "Alice", "age": 20, "grade": "A"}2.) Accessing Items:
print(student["name"]) # Output: Alice3.) Adding/Updating Items:
student["age"] = 21 # Update existing
student["city"] = "NY" # Add new key4.) Looping Through a Dictionary:
for key, value in student.items():
print(key, "=>", value)Other Useful Methods:
- .keys() – returns all keys
- .values() – returns all values
- .get(key) – safely gets value, returns None if key is not found
