For fun, I figured I’d put together a list of responses to some of Google’s autocomplete questions. Today, we’ll look at 10 “how to” python questions.
Table of Contents
Feeding Google Autocomplete
As anyone who has every used Google knows, whenever you start filling out the search box, Google tries to guess what you’re thinking. If you’re not familiar with this feature, here’s a fun example with Daniel Radcliffe:
Now, I’m not sure how this feature works exactly, but I suspect that it generates search queries based on common searches. For example, if I enter the term Python, here’s what I get:
- python download
- python dictionary
- python for loop
- python tutorial
- python certification
- python list
- python range
- python ide
Of course, for this to be interesting, the queries need to be phrased as questions. To do that, we might precede python with a question word like “is”:
- is python object oriented
- is python a compiled language
- is python free
- is python hard to learn
- is python case sensitive
- is python a scripting language
- is python open source
- is python easy to learn
- is python a programming language
- is python a high level language
Now, these are definitely answerable questions! But, they’re mainly yes or no questions that don’t leave a lot for interpretation. For instance, Python is absolutely free. In addition, some of these questions are fairly controversial and open-ended. For example, I might argue that Python is easy to learn, but that might as well be an entire article. As a result, I figured I needed to pick a query string that fit my audience’s needs a bit more.
10 How to Questions From Google
For this article, I figured I’d stick to my niche of how to articles. As a result, I phrased my query as follows: “python how to.” Naturally, this yielded the following questions which we’ll use for this article:
- python how to add to a list
- python how to call a function
- python how to sort a list
- python how to print on same line
- python how to reverse a string
- python how to print
- python how to convert string to int
- python how to write to a file
- python how to install pip
- python how to comment out a block
With further ado, let’s get started!
How to Add to a List
As it turns out, this is a pretty common question. I suspect this gets asked a lot from folks who are used to the array syntax from popular languages like Java and C.
Certainly array syntax works in Python, but the word “add” takes on some additional meaning in Python. After all, Python lists aren’t fixed length. As a result, “add” could mean insert or replace, but it could also mean append. To cover all my bases, I’ll show all three.
Up first, let’s talk about the main way to add to a list:
append(). As the name implies,
append() will add an item to the end of a list. Let’s see it in action:
numbers = [1, 4, 3] numbers.append(8) # stores [1, 4, 3, 8]
Once we have a list, we can replace elements using the index directly:
letters = ["b", "x", "f"] letters = "t" # stores ["b", "t", "f"]
Alternatively, we can insert elements anywhere in a list:
colors = ["blue", "red", "purple"] colors.insert(2, "green") # stores ['blue', 'red', 'green', 'purple']
Finally, we can extend a list using another list:
numbers = [1, 4, 3] numbers.extend([3, 2, 1]) # stores [1, 4, 3, 3, 2, 1]
In general, there are a lot of ways we can add to a list. For more information, check out this article covering this exact subject.
How to Call a Function
In Python, functions store a set of instructions. To be able to execute that set of instructions, we have to use the name of the function and a set of parentheses:
In this case, we call the
print() function which creates a newline on the command line.
Of course, not all functions are the same; some take arguments. For example, the
len() function expects an iterable to determine its length. To do that, we have to pass the iterable between the parentheses:
len("Hello!") # returns 6
Some functions accept more than one argument. In those cases, we use commas to separate each argument. For example, the
min() function allows us to pass as many values as we want and returns the smallest one:
min(1, 5, -3) # returns -3
To further complicate things, Python functions can accept keyword arguments. For example, the
print() function we used earlier always prints a newline. However, we can override that by specifying a keyword argument:
In this case, we replace the usual line ending with an empty space. That way, we can call
print() repeatedly without leaving the current line. To learn more about this behavior, check out this article on how to print on the same line.
To summarize, calling a function is as easy as using the name and a set of comma separated arguments.
How to Sort a List
Well, this question sort of raises the stakes a bit! After all, sorting is a deeply complex problem that depends heavily on the type of data we’re dealing with. For instance, if we’re working with numbers, sorting is as straightforward as specifying the desired order. However, if we’re working with data like strings, dictionaries, or objects, the question of sorting becomes significantly more complicated.
As a result, the best way I can answer this question is by introducing the
sort() method of lists. In short, this method will take care of sorting most data for you. For example, if we had a list of numbers,
sort() will sort them using their “natural” order:
numbers = [2, -1, 9, 7] numbers.sort() # stores [-1, 2, 7, 9]
In fact, this same method will work for other types of data including strings:
colors = ["red", "blue", "orange"] colors.sort() # stores ["blue", "orange", "red"]
The reason this works is because the behavior of the relational operators are specified for both strings and numbers. Let’s see what happens when we use a data type that has a bit less of a “natural” ordering:
points = [(1, 2), (3, -2), (2, 2)] points.sort() # stores [(1, 2), (2, 2), (3, -2)]
Here, it appears that the list is now ordered by the first element of each tuple. If we wanted to sort by the second element, we would have to specify that through the key argument:
points = [(1, 2), (3, -2), (2, 2)] points.sort(key=lambda point: point) # stores [(3, -2), (1, 2), (2, 2)]
In short, the key argument accepts a function. In this case, we defined a lambda function inline, but it’s possible to pass a typical function:
def sort_key(point): return point points = [(1, 2), (3, -2), (2, 2)] points.sort(key=sort_key) # stores [(3, -2), (1, 2), (2, 2)]
As you can probably imagine, you can define increasingly complex key functions depending on how you want to sort your data. For example, we could sort these points by the average of their x- and y-coordinates:
def sort_key(point): return (point + point) / 2 points = [(1, 2), (3, -2), (2, 2)] points.sort(key=sort_key) # stores [(3, -2), (1, 2), (2, 2)]
Naturally, I’ve written about sorting quite a bit, so I’ll just drop a few additional references here:
- How to Brute Force Sort a List in Python: Bubble, Insertion, and Selection
- How to Sort a List of Dictionaries in Python: Sort and Sorted
- How to Sort a List of Strings in Python: Sort, Sorted, and More
That said, let’s move on!
How to Print on Same Line
Uh oh! I accidentally answered this one already. That said, I understand why this question gets asked a lot. As it turns out, the default behavior of the
print() function in Python is to end every string with a newline. If you come from a language like Java, you might be familiar with the distinction between “print” and “println” or even “printf”. Python only has
If you’re using the latest version of Python, you should be able to circumvent this issue by overriding the default end string:
If for some reason you’re still using Python 2 despite it being deprecated, you can call
print() with a tuple:
Unfortunately, neither of these solutions work in both Python 2 and 3. As a result, if you need some form of backwards compatibility, you’ll have to use a different function entirely:
import sys sys.stdout.write("Haruhi")
That said, if you need more details about these solutions, you’re welcome to check out this article.
How to Reverse a String
String reversal is sort of a sinister request. After all, strings aren’t as straightforward as we are often led to believe. For example, if you’ve used C, you know that every string ends with a null terminating character. Likewise, many strings include invisible characters as well as characters that are composed of characters.
That said, Python 3 does an excellent job of abstracting a lot of these challenges. As a result, reversing a string is as easy as using the extended slice syntax:
name = "Jeremy" name[::-1] # returns "ymereJ"
Normally, a slice is used to extract a segment of a string. However, if we leave out the bounds, we get a copy of our original string. Meanwhile, the extended syntax allows us to specify the step. In our case, a step of -1 allows us to traverse the string one character at a time backwards.
Naturally, there are other options. For example, we can make use of the
reversed() function which creates a list of the characters in reverse order. As a result, to get the string we want, we have to join all the characters:
name = "Jeremy" ''.join(reversed(name)) # returns "ymereJ"
That said, this solution is quite a bit slower than the extended slice syntax. Beyond that, we’d have to write our own solution which tends to be error prone.
How to Print
Again, this is one of those questions that we’ve accidentally discussed a few times. As a result, I won’t dwell on it to much. Just know that there is a function called
print() that we can use to write text to the command line:
Like most built-in functions,
print() has several keyword arguments including “end” which we’ve discussed already. In addition, we can specify the separator between strings. This only works if we provide multiple strings to
print() which Python allows—just like
print("Hi", "I'm", "Paul") # prints "Hi I'm Paul" print("Hi", "I'm", "Paul", sep="--") # prints "Hi--I'm--Paul"
In addition, we can actually specify where print writes. Typically, it’s to standard output (i.e. the command line), but we can force print to write to a file using the “file” keyword argument.
All that said, that’s pretty much the extent of printing.
How to Convert String to Int
Recently, I wrote an article on how to do the exact opposite of this: convert an integer to a string. Regardless, the same principles still apply.
In order to convert a string to an integer, we need to be able to type cast the string value. Fortunately, Python provides the integer constructor which accepts strings:
int("13") # returns 13
Of course, it comes with the usual caveat that the string must be able to be converted to an integer. Otherwise, we’ll get an error.
int("hi!") # throws an error
Interestingly, the integer constructor can actually make sense of a broader array of values than base 10 numbers. For example, we can convert from hexadecimal to integer as follows:
int("FF", base=16) # returns 255
Otherwise, that’s all there is to it!
How to Write to a File
File writing is a tricky subject, but it basically boils down to a two-step process:
- Open a file
- Write to that file
To be honest, the first task is the challenge. After all, depending on your needs, you might need to play around with platforms and paths just to open a file. That said, the quickest way to do it is to use the built-in
Unfortunately, this line alone will open the file in read-only mode, so we can’t actually do any writing. As a result, we’ll have to pass one of the following parameters:
- w: creates a new file or overwrites an existing file for writing content
- a: creates a new file or prepares an existing file for appending content
While there are more options than these two, these are two of the quickest ways to get a file ready for writing. For more details, check out this article on how to open a file. Otherwise, we’ll prep a file for writing as follows:
To use the file for writing, we can call the
write() function on the returned object:
f = open("myfile.txt", mode="w") f.write("Hi!")
Then when we’re done, we can close the file:
f = open("myfile.txt", mode="w") f.write("Hi!") f.close()
Now while I’ve technically answered the question, I feel like there is a bit more worth knowing. For example,
write() takes whatever you write literally. As a result, you have to handle your own formatting including newlines. As an alternative, you can leverage
print() just as you would normally:
f = open("myfile.txt", mode="w") print("Hi!", file=f) f.close()
Also, Python includes the
with statement which helps manage resources like files. Rather than opening and closing files ourselves, we can use this statement to simplify the process:
with open("myfile.txt", mode="w") as f: print("Hi!", file=f)
All that said, I definitely recommend checking out other resources related to this question. The world of Input/Output (I/O) is a bit messy, so you’ll want to make sure you’re comfortable with the basics.
How to Install Pip
If you’ve ever used a third-party library like NumPy or PIL, you know all about pip. It’s the standard package manager that ships with Python, and it allows you to install and maintain libraries—though, I think package management is generally pretty annoying in Python.
That said, the question was not about my take on package management but rather about how to actually install pip. As pip’s documentation states, this shouldn’t really be an issue because “pip is already installed if you are using Python 2 >=2.7.9 or Python 3 >=3.4”. In other words, modern version of Python come preinstalled with pip.
Of course, if you’re on windows, there’s a possibility that pip is not recognized as a valid command. Usually, the quickest way to resolve this is to reinstall Python and make sure to check the box that says “add to PATH.” Alternatively, you can really get into the weeds with setting up environment variables yourself. As someone who has multiple versions of Python installed, I know all about that!
Another workaround is to use an IDE like PyCharm which uses virtual environments to manage your dependencies for you. For every project, you can create a new virtual environment, so all your dependencies are protected.
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
Then, you can install pip (assuming Python is installed and in your PATH) as follows:
That said, I would tend to opt for one of the options above if possible. That’ll mitigate any headaches.
How to Comment Out a Block
For whatever reason, whether it be that Python is “interpreted” or that the Zen of Python states that there should only be one way of doing things, Python has no support for block comments.
Unfortunately, that doesn’t change the reality that people could benefit from some form of block comment syntax. Typically, this type of feature is required because a large chunk of code is to be briefly removed for testing, and a block comment tends to be the quickest and cleanest way of doing that.
However, because there is no block comment syntax, there tend to be two work arounds. First, we can use the repeated comment syntax:
# This # is # a # cool # comment
Alternatively, we can opt for triple-quote strings:
""" This is a cool comment """
In this case, the syntax also pulls double duty with doc strings. In either case, this is as good as it gets in Python. Read more about the options and rationale here.
Interested in Python?
In 2017, I picked up Python for the first time, and I’ve sort of been hooked ever since. As a result, I’ve written a ton about Python which includes things like a series on how to do stuff in Python and a series for people who want to self-learn python—both are ongoing.
If you’re already familiar with Python, I’d love some support with the following repositories:
- Sample Programs: help build out code snippets and documentation in languages like Python
- How to Python Code: help convert existing python snippets into Jupyter notebooks or solve existing #RenegadePython challenges
- Image Titler: help expand a tool for generating featured images
Otherwise, stick around and read some of these related articles:
- Python 3.9 Features That Will Make Your Life Easier
- Can We Fit Rock Paper Scissors in Python in a Tweet?
- What If Python Only Had Functions?
Likewise, here are some resources from the folks at Amazon (#ad):
- Effective Python: 90 Specific Ways to Write Better Python
- Python Tricks: A Buffet of Awesome Python Features
- Python Programming: An Introduction to Computer Science
Finally, here’s a list of the usual ways to support the site (e.g. Discord, Patreon, etc.). As always, thanks for stopping by! I appreciate it.
I don't like to share about personal stuff too much, but I figured I'd share some early news of 2021.
Today, I'm whipping out some philosophy jargon to characterize some of the problems I see in the tech education community.