Back to Python
2026-04-206 min read

Object Display (Python Programming)

Learn Object Display (Python Programming) step by step with clear examples and exercises.

Title: Object Display (Python Programming)

Why This Matters

Understanding object display is crucial for debugging and visualizing data structures, making it an essential skill for Python programmers. It's especially useful in interviews, where you may be asked to demonstrate your understanding of Python's built-in functions for object display. A solid grasp of object display can help you manage complex data structures, improve code readability, and effectively communicate the state of your programs.

In this lesson, we will delve deeper into Python's built-in functions for displaying objects: print(), repr(), and str(). We will also explore how to create custom object representations using these functions.

Prerequisites

Before diving into object display, make sure you have a solid grasp of the following topics:

  1. Basic Python syntax (variables, operators, assignments)
  2. Data structures (lists, tuples, and dictionaries)
  3. Control flow (if-else statements, loops)
  4. Functions and modules
  5. Exception handling
  6. Classes and objects
  7. Modular programming concepts
  8. Understanding the difference between repr() and str() in Python

Core Concept

Python provides several built-in functions for displaying objects: print(), repr(), and str(). These functions are essential tools for Python programmers, helping them debug, visualize data structures, and create custom object representations.

  1. print(): The most commonly used function for displaying data is print(). It can handle various types of data, including strings, numbers, lists, dictionaries, and even custom objects.
x = 5
y = "Hello"
print(x)
print(y)

When you run the above code, Python outputs:

5
Hello
  1. repr(): The repr() function returns a string representation of an object that can be used to recreate the original object when evaluated. It's useful for displaying complex objects, such as lists and dictionaries.
my_list = [1, 2, 3]
print(repr(my_list))

When you run the above code, Python outputs:

[1, 2, 3]
  1. str(): The str() function converts an object to a string. It's often used for custom objects that don't have a predefined string representation.
class MyClass:
def __init__(self, value):
self.value = value

def __repr__(self):
return f"MyClass({self.value})"

def __str__(self):
return f"String representation of MyClass: {self.value}"

my_object = MyClass(42)
print(my_object)

When you run the above code, Python outputs:

MyClass(42)

Customizing Object Representation

For custom objects, it's essential to implement both __repr__ and __str__ methods to provide meaningful representations of your objects. The __repr__ method should return a string that can be used to recreate the object, while the __str__ method is often used for user-friendly string representation.

class MyClass:
def __init__(self, value):
self.value = value

def __repr__(self):
return f"MyClass({self.value})"

def __str__(self):
return f"String representation of MyClass: {self.value}"

my_object = MyClass(42)
print(my_object)

When you run the above code, Python outputs:

MyClass(42)

Worked Example

Let's display a list of dictionaries containing user information and calculate some statistics using repr(), str(), and built-in functions from the statistics module.

from statistics import mean, stdev
import math

users = [
{"name": "Alice", "age": 30, "city": "New York"},
{"name": "Bob", "age": 25, "city": "Los Angeles"},
{"name": "Charlie", "age": 22, "city": "Chicago"}
]

total_age = sum([user["age"] for user in users])
average_age = mean(users, key=lambda user: user["age"])
standard_deviation = math.sqrt(stdev(users, loc=mean(users, key=lambda user: user["age"]), axis=0))
max_age = max([user["age"] for user in users])

print("User list:")
for user in users:
print(f"Name: {user['name']}")
print(f"Age: {user['age']}")
print(f"City: {user['city']}\n")

print("\nTotal age:", total_age)
print("Average age:", average_age)
print("Standard deviation of ages:", standard_deviation)
print("Maximum age:", max_age)

When you run the above code, Python outputs:

User list:
Name: Alice
Age: 30
City: New York

Name: Bob
Age: 25
City: Los Angeles

Name: Charlie
Age: 22
City: Chicago

Total age: 79
Average age: 26.333333333333336
Standard deviation of ages: 4.08248290463863
Maximum age: 30

Common Mistakes

  1. Printing variables without spaces: Remember to add spaces between variables when using print().
x = 5
y = "Hello"
print(x) # Output: 5
print(y) # Output: Hello
print(x, y) # Output: 5 Hello
  1. Not using f-strings: Using f-strings makes your code more readable and easier to format.
x = 5
y = "Hello"
print("The number is: ", x) # Output: The number is: 5
print(f"The number is: {x}") # Output: The number is: 5
  1. Not handling exceptions: When dealing with user input or external data, it's important to handle potential exceptions to ensure your program doesn't break unexpectedly.
  1. Not understanding the difference between repr() and str(): Both repr() and str() return strings, but repr() returns a more verbose representation that can be used to recreate the original object when evaluated, while str() is often used for custom objects and provides a user-friendly string representation.
  1. Not implementing __repr__ and __str__ methods for custom classes: When you create a custom class, it's important to implement both the __repr__ and __str__ methods to provide meaningful representations of your objects.

Practice Questions

  1. Write a function that takes a list of numbers and prints the sum, average, and maximum number using functions from the statistics module.
  2. Given a dictionary containing a person's name, age, and favorite programming language, print the person's information in a formatted way using f-strings.
  3. Create a class for a Car object with attributes make, model, year, and miles driven. Implement a __str__ method to display the car's information and a drive() method that increments the mileage by a specified amount.
  4. Write a function that takes a list of dictionaries containing user data and calculates the average age for each city.

Subheadings under Practice Questions:

  • Using the statistics module to calculate sum, average, and maximum number from a list of numbers
  • Formatting person's information using f-strings
  • Creating a Car class with __str__ method and drive() method
  • Calculating average age for each city in a list of user data

FAQ

  1. Why can't I use print() on complex objects without quotes?
  • Python automatically converts complex objects (like lists and dictionaries) to strings using their repr() representation when you try to print them without quotes. To avoid this, you should use print(repr()) or format the object as a string manually.
  1. What's the difference between repr() and str()?
  • Both repr() and str() return strings, but repr() returns a more verbose representation that can be used to recreate the original object when evaluated, while str() is often used for custom objects and provides a user-friendly string representation.
  1. Why should I use f-strings instead of % formatting?
  • F-strings are preferred over % formatting because they are easier to read, less error-prone, and more flexible. They also support positional and named arguments, making them a better choice for most cases.
  1. Why should I use the statistics module instead of built-in functions like sum() and max()?
  • The statistics module provides additional functionality, such as calculating the mean (average) and variance, which can be useful when working with statistical data. Using the statistics module makes your code more efficient and easier to read, as you don't have to write multiple lines of code for simple calculations like sum and max.
Object Display (Python Programming) | Python | XQA Learn