Built-in Functions and Methods
Here’s a code snippet showing the example code used in this lesson:
words = ["cat", "dog", "horse", "human"]
# Bad
# longer_word = ""
# for word in words:
# longer_word += word
# print(longer_word)
# Good
print(" ".join(words))
00:00 In this lesson, I want to show you why you should be using built-in methods and functions in Python. You’ll see why in an example of concatenating strings that are inside of a list.
00:12
Here, you have a list called words
that contains a couple of strings: "cat"
, "dog"
, "horse"
, "human"
.
00:18 You want to put all of these strings together into a single string. Now, you could do this in a way where you create a new variable as an empty string and then you iterate over all of these items in the list and you just add each item here to the empty string variable that you created earlier. And if you run this, you get the expected output. So, I can say…
00:42 When I run this script, you get this one string that has all of these string items stuck together. And that works, and it’s fine to do it like that, but there’s better ways of doing it in Python that are more idiomatic.
00:54
So let me show you how you can do this by using a string method that is called .join()
, and you can use it on string objects and pass it an iterable—for example, this list—as an argument, and it then just sticks all of these items that are inside of the list together.
01:10
So if I run this script now, you’ll see I get the exact same output as before. All of the items of the words
list are stuck together into one string and printed out. And you have some advantages here. For example, it is pretty easy that you would just want to add a space in between each of those items. You could say, instead of concatenating to the empty string (""
), you want to use a space, a whitespace character (" "
).
01:36
And now if I run this script again, you can see that the output makes sense. You get cat
, space, dog
, space, horse
, space, human
.
01:44 This should serve as an example to show you that even though there’s usually some ways that you can write quite a bit of code with some logic in it to achieve something, very often, there is a method or a function in Python that is built-in and that is just meant to do what you want to achieve in a quicker and easier-readable kind of way.
02:04 This is because Python is a high-level programming language and it has a couple of layers of abstraction on top just to make writing code more readable and also more enjoyable for you.
02:15 So, keep that in mind—that if there’s something you want to do, first check is there a method or is there a built-in function in Python that does exactly what you wanted to do.
Become a Member to join the conversation.