Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

The DRY Principle

Here’s a code snippet showing the example code used in this lesson:

guest = "Peter"

# Bad: Repeated code

# if guest == "Mia" or guest == "John" or guest == "Linda":
#     print("yay!")

# Good: DRY

friends = ["Mia", "John", "Linda", "Peter"]

if guest in friends:

00:00 In this lesson, I want to talk to you about how you can apply the DRY principle, which stands for Don’t Repeat Yourself, with Pythonic code.

00:09 So, in this example, you have a guest coming through the door and there’s a couple of people that you like, and that you’re happy to meet, which would be "Mia", "John", and "Linda".

00:17 And in this snippet, you just want to check, is the guest coming through the door one of those people, and if so, then you’re happy and you write out, "yay!".

00:25 So if you run this code at the moment, you can be happy because "Linda" came through the door. But now let’s say "Peter" comes instead, and you just don’t like "Peter" that much, so you don’t want to jump into the air and scream "yay!" really loudly.

00:39 Okay, but this is a lot of code that you needed to use to make that check, and a lot of it is repeated. You can see VS Code already highlights all of that for me and shows me that this is the same over and over again.

00:52 Especially, let’s say, if you would start liking "Peter" and you want to add him to this, you’d just have to repeat even some more code. Okay, you’d have to say or guest == "Peter". And you see, like, this is already running out of the screen because it gets so long, ha.

01:06 So, let’s not repeat ourselves and use a different, more Pythonic way of doing this.

01:15 What you can do instead is you can have a list of your friends, which has "Mia", "John", "Linda" in there, and let’s add "Peter" to it as well.

01:24 And then you can just say, if the guest that comes through the door

01:30 is in your friends list, then you want to jump up and print "yay!". You can see this is much more extensible. You can easily add just a single name to the list, and the conditional statement here still works as expected. So if you run this, now since you started liking "Peter", you can still jump up into the air.

01:51 So, this is just to exemplify that there’s ways that you can write Python code that avoids repetition. Like here, you achieved the same thing, but it was a lot of repeated code.

02:00 And here, you wrote it in a way that is much more concise, easier, extensible, less prone to errors, lots of stuff like that that is all part of the Don’t Repeat Yourself principle, and this would be a Pythonic way of applying it.

Become a Member to join the conversation.