Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Built-In Data Types
  5. Range and Dictionary in Python

Range and Dictionary in Python

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
  8

Convert to list:

print(list(range(5)))  # Output: [0, 1, 2, 3, 4]

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: Alice

3.) Adding/Updating Items:

student["age"] = 21      # Update existing
student["city"] = "NY"   # Add new key

4.) Looping Through a Dictionary:

for key, value in student.items():
    print(key, "=>", value)
  • .keys() – returns all keys
  • .values() – returns all values
  • .get(key) – safely gets value, returns None if key is not found

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *