Register to get access to free programming courses with interactive exercises

Chain of methods Python Basics

In this lesson, we will look at how to combine different approaches when writing code. Also, we will cover common beginner errors.

Here we have the following code:

name = 'Tirion'
print(name.upper().lower())  # => `tirion`

It prints tirion on the screen.

All operations above are familiar, but we see several consecutive periods for the first time. This code combines the Python features that we currently know.

It often happens in programming. When you do not know the syntax, you can combine different approaches. There is a chance they will work.

Let us figure out how this code works. We need to break down the chain into separate operations:

name = 'Tirion'
upper_name = name.upper()  # 'TIRION'
print(upper_name.lower())  # 'tirion'

The first and second examples are equivalent. We can choose from two options:

  • Perform operations sequentially by creating intermediate variables
  • Build a continuous chain of attributes and methods that goes from left to right, like computations in chains always do

Here you see another example to get across the idea:

name = 'Tirion'
print(name.replace('Ti', 'Ki').lower())  # => ?

This code needs a lot of thought. The .lower() function applies to the result of the method call, which is on the left. And the replace() method returns a string.

Beginners often make mistakes in method chains and forget to place a call:

name = 'Tirion'
# This code will not work properly
print(name.upper.lower())

Do not forget about the risk of building infinitely long and useless chains with slices:

# What is the result of this call?
print(name[1:5].upper().find('I'))

It will not work with functions since programmers usually nest them inside each other — f(f(f())). It makes the analysis much more difficult. But it doesn't mean we cannot do it nicely. We can implement this feature in other languages through a function composition or a pipelining operator.

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY