A lambda function allows you to define a function in a single line. It starts with the keyword lambda, followed by a comma-separated list of zero or more arguments, followed by the colon and the return expression. For example, lambda x, y: x+y calculates the sum of the two argument values x+y in one line of Python code.
Problem: How to define a function in a single line of Python code?
Example: Say, you’ve got the following function in three lines. How to compress them into a single line of Python code?
def say_hi(*friends): for friend in friends: print('hi', friend) friends = ['Alice', 'Bob', 'Ann']
say_hi(*friends)
The code defines a function say_hi that takes an iterable as input—the names of your friends—and prints 'hi x' for each element x in your iterable.
The output is:
'''
hi Alice
hi Bob
hi Ann '''
Let’s dive into the different methods to accomplish this! First, here’s a quick interactive overview to test the waters:
Exercise: Run the code—is the output the same for all four methods?
Next, you’ll learn about each method in greater detail!
A lambda function is an anonymous function in Python. It starts with the keyword lambda, followed by a comma-separated list of zero or more arguments, followed by the colon and the return expression. For example, lambda x, y, z: x+y+z would calculate the sum of the three argument values x+y+z.
friends = ['Alice', 'Bob', 'Ann'] # Method 1: Lambda Function
hi = lambda lst: [print('hi', x) for x in lst]
In the example, you want to print a string for each element in an iterable—but the lambda function only returns an object. Thus, we return a dummy object: a list of None objects. The only purpose of creating this list is to execute the print() function repeatedly, for each element in the friends list.
You obtain the following output:
hi(friends) '''
hi Alice
hi Bob
hi Ann '''
Method 2: Function Definition
A similar idea is employed in this one-liner example—but instead of using a lambda function, we define a regular function and simply skip the newline. This is possible if the function body has only one expression:
friends = ['Alice', 'Bob', 'Ann'] # Method 2: Function Definition
def hi(lst): [print('hi', x) for x in lst]
The output is the same as before:
hi(friends) '''
hi Alice
hi Bob
hi Ann '''
This approach is more Pythonic than the first one because there’s no throw-away return value and it’s more concise.
To make a Python one-liner out of any multi-line Python script, replace the new lines with a new line character '\n' and pass the result into the exec(...) function. You can run this script from the outside (command line, shell, terminal) by using the command python -c "exec(...)".
We can apply this technique to the first example code snippet (the multi-line function definition) and rename the variables to make it more concise:
friends = ['Alice', 'Bob', 'Ann'] # Method 3: exec()
exec("def hi(*lst):\n for x in lst:\n print('hi', x)\nhi(*friends)")
If you run the code, you’ll see the same output as before:
hi(friends) '''
hi Alice
hi Bob
hi Ann '''
This is very hard to read—our brain cannot grasp the whitespaces and newline characters easily. But I still wanted to include this method here because it shows how you or anyone else can compress complicated algorithms in a single line of Python code!
Watch the video if you want to learn more details about this technique:
Python One-Liners Book
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:
• Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
You may know the following problem: You have an object’s attribute name as a string—say, you’ve read it from a file—and you want to access the attribute with the given name. But you cannot use the syntax object."attribute" because the dot notation only allows for name-access like this: object.attribute. How do you resolve this problem? This article will show you how!
Quick Solution: There are four ways to access the object attribute in Python via the built-in functions:
hasattr()— checks whether an attribute exists or not,
setattr()— is used for setting an attribute, if the attribute does not exist, it will be created,
delattr()— deletes the attribute.
What Are Attributes Anyways?
We callattributeeverything is contained inside an object in Python. There is no real distinguishing between plain data and functions—both are objects. Thus, everything you’ll learn about attributes also applies to methods.
In this article, I will use the following class to show how to access the attributes. It represents a gun of some name and its caliber. In addition, it provides a get_entry method which returns a string representation of the weapon.
class Gun: def __init__(self, name, caliber): self.name = name self.caliber = caliber
The Getattr() Function
As mentioned above, the getattr() function allows you to access the class object attribute. Its syntax is getattr(object, attribute, default), the first two parameters are required, and the third is optional.
object – an object of the class which has been created,
attribute – the name of the attribute from which you want to get the value,
default – message that will be printed out if the attribute does not exist.
ak47 = Gun(name='Ak-47', caliber='7,62 mm') print(getattr(ak47, 'caliber', f'the attribute named {"caliber"} does not exist')) print(getattr(ak47, 'color', f'the attribute named {"color"} does not exist'))
Output:
7,62 mm
the attribute named color does not exist
You first create a Gun class object. Second, you get its caliber and color. Since your object does not have an attribute called color, you only received its caliber and information that the attribute named color does not exist.
You can run this code in our interactive Python shell:
Exercise: Change the output to also print the name of the object.
The Hasattr() Function
The hasattr() function checks if the attribute exists and prints out the bool value: True if so or False if it does not exist. This function has only two parameters that need to be specified: object and attribute.
attributes = ['name', 'color', 'caliber', 'designer'] for attribute in attributes: print(hasattr(ak47, attribute))
Output:
True
False
True
False
As we can see, the hasattr() function checked whether our object named ak47 has the attributes we included in the list and returned True and False values to us. This function is especially useful when we have written many lines of code and our project is huge, then we can quickly and easily check if an object has some attribute or even several attributes.
The Setattr() Function
The setattr() function sets an attribute. Moreover, if the attribute does not exist, it will be created. There are three parameters, and all are required:
object – object of your class,
attribute – name of the attribute you want to set,
value – the value you want to give to the attribute.
As you can see, the function fulfilled its role. At the beginning, we checked if the attribute named mass exists and at that time it did not exist yet (False), then we set the value for this attribute and as we can see, after using setattr(), the object obtained a new attribute (True).
The Delattr() Function
The delattr() function deletes a given attribute from a specific object. Just like with hasattr(), the parameters are two – object and attribute.
ak47 = Gun('ak47', '7,62 mm') attributes = ['name', 'caliber'] for attribute in attributes: print(hasattr(ak47, attribute)) for attribute in attributes: delattr(ak47, attribute) print('***') for attribute in attributes: print(hasattr(ak47, attribute))
Output:
True
True
***
False
False
At first, we created a Gun class object and a list with attribute names. Later we checked if the object has these attributes (True, True), then we used delattr() in the for loop and checked again (False, False).
Other Methods To Access Object Attribute:
Finally, you must also provide another way to check/change the value of the attribute or delete the attribute completely.
You can also access the attribute using dotted-syntax:
This way it also works, but remember that it can cause Error when a given attribute does not exist (this cannot be prevented as easily as with the built-in functions) and additionally we can’t check the value of several objects at once using the loop, so we have to use the getattr() function.
You can delete an attribute using the delfunction:
ak47 = Gun('ak47', '7,62 mm') attributes = ['name', 'caliber'] for attribute in attributes: print(hasattr(ak47, attribute)) del ak47.name
del ak47.caliber print('***') for attribute in attributes: print(hasattr(ak47, attribute))
Output:
True
True
***
False
False
As we can see, we have managed to delete, but we have to call the attributes one by one, so if we want to delete more attributes, it is better to use the delattr() function and the for loop.
Summary
We started with an explanation of what the attributes in Python are, and then the functions getattr(), hasattr(), setattr() and delattr() were described. Finally, we presented other methods with the help of which you can see/change the value of an attribute and also remove an attribute completely.
I hope this article has answered all your questions about how to access an object attribute.
When Guido van Rossum released the first viable Python version 0.9.0 in 1991, he couldn’t have expected (by a long shot) that he was on the verge of creating the most influential programming language in the world. Python has a bright future: every new Python version adds new features to the programming language.
In this quickstart guide, you’ll learn how to set up Python on your computer and install the newest version. Because Python is constantly evolving, we keep this information as generalized as possible.
So, how to get started with Python? Let’s go over the steps one by one.
Step 1: Download Python
First, please visit the official Python website and download the latest Python version. The download manager should already propose the correct installer for your operating system because it receives this information through your browser accessing the site.
Step 2: Install Python on Your Machine
Second, run the installer on your computer. In most operating systems, there’s nothing more to it than double clicking the downloaded file.
Step 3: Check Your Python Installation
Third, check if your Python installation worked properly by running the following command in your command line or PowerShell (Windows), terminal (MacOS), or shell (Linux).
Here’s a screenshot checking the Python version on my Windows machine:
Congratulations, you have installed Python on your computer!
Step 4: Write Your First Hello World Program with IDLE
You can start writing your own programs with the IDLE editor that’s built into your system. Just search the phrase ‘IDLE’ on your operating system and open the program:
To start your first own program, type the following command into your shell:
>>> print('hello world!')
Python will interpret your command and print the desired words to your shell:
hello world!
This mode of communicating back-and-forth with your Python interpreter is called “interactive mode”. It has the advantage of immediate feedback. However, the great things about programs is automation—writing a program once and running it again and again.
For example, how to write a program that greets you by name every time you run it?
Step 5: Create Your First Python Module
To allow you to write a program once, save it on your computer, and run it at any later point in time, Python comes with what you may call a “scripting mode”. In this mode, you write a Python script and store it in a file with the suffix .py such as my_first_program.py.
You can create such a file via the menu of your IDLE shell:
Click “New File” and copy&paste the following code into your new file:
name = input("What's your name? ")
print('hello ' + name)
You’ll learn about the commands of the Python programming language in my free email academy (with cheat sheets). For now, please store your file under the name 'hello.py' on your Desktop or any other location. Your current state should look like this:
You can test-run this program here in your browser in our interactive Python shell:
Exercise: Run the code and type in your name. What’s the output?
Step 6: Run Your First Module
Now, let’s get some action going: Click Run > Run Module. The Python program start executing in the interactive shell—but without you needing to type each line into it. It runs through the code file line by line. The first line asks you to put in your name. Type it in. The second line then takes your name and prints it to the shell. Here’s how this looks in my case:
Conclusion
Believe it or not, this procedure will later allow you to run your own applications. Although the applications will get more complicated, the basic process looks the same: First, you create a Python file that contains the application. Second, you run the application on your computer. Theoretically, you don’t need any other Python editor – the preinstalled IDLE editor is all you need!
While this is already a great accomplishment for the day, most coders don’t use the built-in Python editor IDLE a lot. Why? Because it’s harder with the IDLE editor to write simple programs and the editor doesn’t provide you with advanced tools, assistance, and language support. Instead, a far better option for most coders will be to install an integrated development environment (IDE). One of the most popular for Python is PyCharm.
However, this is an optional step and different coders prefer different development environments. You can find detailed installation and setup guides online. We recommend you follow these instructions to set up your own PyCharm projects. Even if this takes you an hour or so to complete, it’s a good investment in your future productivity!
Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
To sort and return a Python list in a single line of code, use the sorted(list) method that returns a new list of sorted elements. It copies only the references to the original elements so the returned list is not a deep but a shallow copy.
Let’s dive into the challenge to learn about more details and alternatives. Everything is not always simple. By studying the different methods that solves this, you’ll become a better coder!
You want to sort this list and return the result in a single line. If you use the list.sort() method, the return value is None:
print(a.sort())
# None
The return value of the list.sort() method is None, but many coders expect it to be the sorted list. So they’re surprised finding out that their variables contain the None type rather than a sorted list.
However, returning None makes perfect sense for the list.sort() method. Why? Because you call the method on a list object and it modifies this exact list object. It doesn’t create a new list—there won’t be a new list object in memory.
So, how to sort and return a list in a single line of Python code? As a rule of thumb, there are always multiple ways to accomplish the same thing in Python. Let’s dive into the different ways to accomplish this!
Here’s a quick overview of the methods addressed in this article:
Exercise: Change the list to be sorted by adding negative floats. Does it still work?
You’ll now learn more about each of the methods.
Method 1: sorted()
The easiest way to accomplish this task is to call Python’s built-in sorted() function that takes an iterable and returns a new list with sorted elements.
The sorted() function generates a new sorted list that is put into the print() function that prints the sorted list to the shell. The output is the sorted list:
[1, 2, 3, 4]
This method is the most Pythonic one. But are there alternatives?
Method 2: list.sort() + Ternary Operator
The sorted() method leaves the original list unchanged. But what if you want to sort the original list and get this original list as an output that you can assign to a variable?
a = [4, 2, 1, 3] # Method 2: list.sort() + ternary
print(a if a.sort() else a)
# [1, 2, 3, 4]
You need to understand two concepts: (1) list.sort() and (2) the ternary operator:
The list.sort() method sorts the list elements in place in an ascending manner. To customize the default sorting behavior, use the optional keyargument by passing a function that returns a comparable value for each element in the list.
The ternary operatorx if c else y consists of three operands x, c, and y. It returns x if the Boolean expression c evaluates to True. Otherwise, if the expression c evaluates to False, the ternary operator returns the alternative y.
The beautiful thing is that the one-linerprint(a if a.sort() else a) modifies the original list and returns it right away. How does it do this?
Explanation: First, the a.sort() method is called to check which “branch” of the ternary operator should be visited. The return value of a.sort() will always be None. The None value is automatically converted to the Boolean False. Thus, the ternary operator always returns the list object referred to by variable a.
Note that the only purpose of the ternary operator is to make sure to call the a.sort() method before returning the value a—to make sure it is sorted!
If you print the original list to the shell, you’ll see that it is now sorted:
>>> print(a)
[1, 2, 3, 4]
Method 3: Combining Multiple Statements in a Single Line with Semicolon
An alternative is chaining the statements with a semicolon ; to one-linerize a Python code snippet. This strategy works with flat Python programs without, possible nested, blocks:
If you need to sort a Python list and print its return value to the shell—for example because you run this command from the command line or terminal—you can use this excellent strategy.
You can learn more about how to one-linerize any Python program in my following video:
Python One-Liners Book
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:
• Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
Article summary: Here’s a quick visual overview of the contents of this tutorial.
Flat List: To sum over a list of numbers in a single line of Python code, use Python’s built-in function sum(list).
Nested List: To sum over a list of lists in one line Python, use a generator expression to flatten the list and pass the result into the function: sum(x for y in list for x in y).
Method 1: Sum over a Flat List in One Line
Problem: How to sum over all values in a given Python list?
Example: Given the following list.
a = [1, 2, 3]
You want to calculate the sum of all values in the list—using only a single line of Python code!
# RESULT: 6
Solution: Python’s built-in sum() function helps you to sum over all values in an iterable, such as a Python list.
Summing up a list of numbers appears everywhere in coding. Fortunately, Python provides the built-in sum() function to sum over all elements in a Python list—or any other iterable for that matter. (Official Docs)
Code: Here’s the minimal code example.
a = [1, 2, 3] print(sum(a))
# 6
How does it work? The syntax is sum(iterable, start=0):
Argument
Description
iterable
Sum over all elements in the iterable. This can be a list, a tuple, a set, or any other data structure that allows you to iterate over the elements. Example: sum([1, 2, 3]) returns 1+2+3=6.
start
(Optional.) The default start value is 0. If you define another start value, the sum of all values in the iterable will be added to this start value. Example: sum([1, 2, 3], 9) returns 9+1+2+3=15.
Exercise: Try to modify the sequence so that the sum is 30 in our interactive Python shell:
Method 2: Sum over a Nested List of Lists in One Line
Problem: Given multiple lists in a list of lists. How can you sum over all values in a list of lists such as [[1, 2], [3, 4], [5, 6]] in Python?
Solution: Use a generator expression to flatten the values in the nested list and pass the resulting iterable into the sum() function.
Code: The following code creates a list of lists:
a = [[1, 2], [3, 4], [5, 6]]
To sum over the values in the list of lists, use the following one-liner:
print(sum(x for y in a for x in y))
The output is printed on the shell:
# OUTPUT: 21
But how does it work? The main part of the code is the generator expression x for y in a for x in y that flattens the list.
The part x for y in a for x in y iterates over all elements y in the nested list a.
The part x for y in a for x in y iterates over all elements y in the inner list y.
The part x for y in a for x in y stores the inner element in the iterable.
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:
• Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
Python provides fantastic string formatting options, but what if you need greater control over how values are presented? That’s where format specifiers come in.
This article starts with a brief overview of the different string formatting approaches. We’ll then dive straight into some examples to whet your appetite for using Python’s Format Specification Mini-Language in your own projects.
But before all that—let’s play with string formatting yourself in the interactive Python shell:
Exercise: Create another variable tax and calculate the tax amount to be paid on your income (30%). Now, add both values income and tax in the string—by using the format specifier %s!
Don’t worry if you struggle with this exercise. After reading this tutorial, you won’t! Let’s learn everything you need to know to get started with string formatting in Python.
String Formatting Options
Python’s string formatting tools have evolved considerably over the years.
The oldest approach is to use the % operator:
>>> number = 1 + 2
>>> 'The magic number is %s' % number 'The magic number is 3'
(The above code snippet already includes a kind of format specifier. More on that later…)
The str.format() method was then added:
>>> 'The magic number is {}'.format(number) 'The magic number is 3'
Most recently, formatted string literals (otherwise known as f-strings) were introduced. F-strings are easier to use and lead to cleaner code, because their syntax enables the value of an expression to be placed directly inside a string:
>>> f'The magic number is {number}' 'The magic number is 3'
Other options include creating template strings by importing the Template class from Python’s string module, or manually formatting strings (which we’ll touch on in the next section).
If this is all fairly new to you and some more detail would be helpful before moving on, an in-depth explanation of the main string formatting approaches can be found here.
Format Specifiers
With that quick summary out of the way, let’s move on to the real focus of this post – explaining how format specifiers can help you control the presentation of values in strings.
F-strings are the clearest and fastest approach to string formatting, so I will be using them to illustrate the use of format specifiers throughout the rest of this article. Please bear in mind though, that specifiers can also be used with the str.format() method. Also, strings using the old % operator actually require a kind of format specification – for example, in the %s example shown in the previous section the letter s is known as a conversion type and it indicates that the standard string representation of the object should be used.
So, what exactly are format specifiers and what options do they provide?
Simply put, format specifiers allow you to tell Python how you would like expressions embedded in strings to be displayed.
Percentage Format and Other Types
For example, if you want a value to be displayed as a percentage you can specify that in the following way:
>>> asia_population = 4_647_000_000
>>> world_population = 7_807_000_000
>>> percent = asia_population / world_population
>>> f'Proportion of global population living in Asia: {percent:.0%}' 'Proportion of global population living in Asia: 60%'
What’s going on here? How has this formatting been achieved?
Well the first thing to note is the colon : directly after the variable percent embedded in the f-string. This colon tells Python that what follows is a format specifier which should be applied to that expression’s value.
The % symbol defines that the value should be treated as a percentage, and the .0 indicates the level of precision which should be used to display it. In this case the percentage has been rounded up to a whole number, but if .1 had been specified instead the value would have been rounded to one decimal place and displayed as 59.5%; using .2 would have resulted in 59.52% and so on.
If no format specifier had been included with the expression at all the value would have been displayed as 0.5952350454720123, which is far too precise!
(The % symbol applied in this context should not be confused with the % operator used in old-style string formatting syntax.)
Percentage is just the tip of the iceberg as far as type values are concerned, there are a range of other types that can be applied to integer and float values.
For example, you can display integers in binary, octal or hex formats using the b, o and x type values respectively:
For a full list of options see the link to the relevant area of the official Python documentation in the Further Reading section at the end of the article.
Width Format, Alignment and Fill
Another handy format specification feature is the ability to define the minimum width that values should take up when they’re displayed in strings.
To illustrate how this works, if you were to print the elements of the list shown below in columns without format specification, you would get the following result:
As you can see, width is specified by adding a number after the colon.
The new output is better, but it seems a bit strange that the titles are aligned to the left while the numbers are aligned to the right. What could be causing this?
Well, it’s actually to do with Python’s default approach for different data types. String values are aligned to the left as standard, while numeric values are aligned to the right. (This might seem slightly odd, but it’s consistent with the approach taken by Microsoft Excel and other spreadsheet packages.)
Fortunately, you don’t have to settle for the default settings. If you want to change this behavior you can use one of the alignment options. For example, focusing on the first column only now for the sake of simplicity, if we want to align the number to the left this can be done by adding the < symbol before the p_num variable’s width value:
Python’s default fill character is a space, and that’s what has so far been used when expanding the width of our values. We can use almost any character we like though. It just needs to be placed in front of the alignment option. For example, this is what the output looks like when an underscore is used to fill the additional space in the title row of our column:
It’s worth noting that the same output can be achieved manually by using the str() function along with the appropriate string method (in this case str.center()):
But the f-string approach is much more succinct and considerably faster to evaluate at run time.
Of course, outputting data formatted into rows and columns is just one example of how specifying width, alignment and fill characters can be used.
Also, in reality if you are looking to output a table of information you aren’t likely to be using a single print() statement. You will probably have several rows and columns to display, which may be constructed with a loop or comprehension, perhaps using str.join() to insert separators etc.
However, regardless of the application, in most instances using f-strings with format specifiers instead of taking a manual approach will result in more readable and efficient code.
24-Hour Clock Display
As another example, let’s say we want to calculate what the time of day will be after a given number of hours and minutes has elapsed (starting at midnight):
So far so good. Our program is correctly telling us that after 54 hours and 128 minute the time of day will be 8 minutes past 8 in the morning, but the problem is that it’s not very easy to read. Confusion could arise about whether it’s actually 8 o’clock in the morning or evening and having a single digit to represent the number of minutes just looks odd.
To fix this we need to insert leading zeros when the hour or minute value is a single digit, which can be achieved using something called sign-aware zero padding. This sounds pretty complicated, but in essence we just need to use a 0 instead of one of the alignment values we saw earlier when defining the f-string, along with a width value of 2:
>>> f'{hour:02}:{minute:02}' '08:08'
Hey presto! The time is now in a clear 24-hour clock format. This approach will work perfectly for times with double-digit hours and minutes as well, because the width value is a maximum and the zero padding will not be used if the value of either expression occupies the entire space:
The longer numbers get the harder they can be to read without thousand separators, and if you need to insert them this can be done using a grouping option:
>>> proxima_centauri = 40208000000000
>>> f'The closest star to our own is {proxima_centauri:,} km away.' 'The closest star to our own is 40,208,000,000,000 km away.'
You can also use an underscore as the separator if you prefer:
>>> f'The closest star to our own is {proxima_centauri:_} km away.' 'The closest star to our own is 40_208_000_000_000 km away.'
Putting It All Together
You probably won’t need to use a wide variety of format specification values with a single expression that often, but if you do want to put several together the order is important.
Staying with the astronomical theme, for demonstration purposes we’ll now show the distance between the Sun and Neptune in millions of kilometers:
As you can see, reading from right to left we need to place the n_dist format specification values in the following order:
Type – f defines that the value should be displayed using fixed-point notation
Precision – .1 indicates that a single decimal place should be used
Grouping – , denotes that a comma should be used as the thousand separator
Width – 15is set as the minimum number of characters
Align – ^defines that the value should be centered
Fill – ~indicates that a tilde should occupy any unused space
In general, format values that are not required can simply be omitted. However, if a fill value is specified without a corresponding alignment option a ValueError will be raised.
Final Thoughts and Further Reading
The examples shown in this article have been greatly simplified to demonstrate features in a straightforward way, but I hope they have provided some food for thought, enabling you to envisage ways that the Format Specification Mini-Language could be applied in real world projects.
Basic columns have been used to demonstrate aspects of format specification, and displaying tabular information as part of a Command Line Application is one example of the ways this kind of formatting could be employed.
If you want to work with and display larger volumes of data in table format though, you would do well to check out the excellent tools provided by the pandas library, which you can read about in these Finxter articles.
Also, if you would like to see the full list of available format specification values they can be found in this section of the official Python documentation.
The best way to really get the hang of how format specifiers work is to do some experimenting with them yourself. Give it a try – I’m sure you’ll have some fun along the way!
To accept valid inputs from the user either use a While Loop With Custom Validations or use the PyInputPlus module to avoid tedious validation definitions. Some other methods may also fascinate you which have been discussed below.
Problem: Given a user input; accept the input only if it is valid otherwise ask the user to re-enter the input in the correct format.
Any user input must be validated before being processed, without proper validation of user input the code is most certainly going to have errors or bugs. The values that you want a user to enter and the values that they provide as an input can be completely different. For example, you want a user to enter their age as a positive valid numerical value, in this case, your code should not accept any invalid input like a negative number or words.
#note: In Python 2.7, raw_input() is used to get a user input whereas in python 3 and above input() is used to get user input. input() always converts the user input into a string, so you need to typecast it into another data type if you want to use the input in another format.
Example:
age = int(input("What is your age: "))
if age >= 18: print("You are an Adult!")
else: print("You are not an Adult!")
Output:
What is your age: 25
You are an Adult!
However, the code does not work when the user enters invalid input. (This is what we want to avoid. Instead of an error, we want the user to re-enter a valid input.)
What is your age: twenty five
Traceback (most recent call last): File "C:/Users/Shubham-PC/PycharmProjects/pythonProject/main.py", line 1, in <module> age = int(input("What is your age: "))
ValueError: invalid literal for int() with base 10: 'twenty five'
Now that we have an overview of our problem, let us dive straight into the solutions.
Let’s get a quick overview of the first two solutions discussed in this article:
Method 1: Implement Input Validation Using While Loop And Exception Handling
The easiest solution is to accept user input in a while loop within a try statement and use continue when the user enters invalid input and break statement to come out of the loop once the user enters a valid or correct input value.
Let us have a look at the following code to understand this concept:
Exercise: Run the code and try to break it by using wrong inputs. What happens?
Here’s the code to copy&paste:
while True: try: age = int(input("What is your age: ")) except ValueError: print("Please Enter a valid age.") continue else: if age > 0: break else: print("Age should be greater than 0!")
if age >= 18: print("You are an adult!")
else: print("You are not an adult!")
Output:
What is your age: twenty five
Please Enter a valid age.
What is your age: -25
Age should be greater than 0!
What is your age: 25
You are an adult!
Method 2: Using Python’s PyInputPlus module
Another way of managing user inputs is by using the PyInputPlus module which contains functions for accepting specific data inputs from the user like numbers, dates, email addresses, etc. You can read more about this module in the official documentation here.
Using the PyInputPlus module function we can ensure that the user input is valid because if a user enters invalid input, PyInputPlus will prompt the user to re-enter a valid input. Let us have a look at the code given below to get a better grip on the usage of PyInputPlus for validating user input.
Disclaimer: PyInputPlus is not a part of Python’s standard library. Thus you have to install it separately using Pip.
import pyinputplus as pyip # User is prompted to enter the age and the min argument ensures minimum age is 1
age = pyip.inputInt(prompt="Please enter your age: ", min=1)
if age >= 18: print("You are an Adult!")
else: print("You are not an Adult!")
Output:
Please enter your age: -1
Number must be at minimum 1.
Please enter your age: twenty five 'twenty five' is not an integer.
Please enter your age: 25
You are an Adult!
Method 3: Implementing Recursion
Another way of prompting the user to enter a valid input every time the user enters an invalid value is to make use of recursion. Recursion allows you to avoid the use of a loop. However, this method works fine most of the time unless the user enters the invalid data too many times. In that case, the code will terminate with a RuntimeError: maximum recursion depth exceeded.
def valid_input(): try: age = int(input("Enter your Age: ")) except ValueError: print("Please Enter a valid age. The Age must be a numerical value!") return valid_input() if age <= 0: print("Your Age must be a positive numerical value!") return valid_input() else: return age x = valid_input()
if x >= 18: print("You are an Adult!")
else: print("You are not an Adult!")
Output:
Enter your Age: -1
Your Age must be a positive numerical value!
Enter your Age: twenty five
Please Enter a valid age. The Age must be a numerical value!
Enter your Age: 25
You are an Adult!
Method 4: A Quick Hack Using Lambda Function
Though this method might not be the best in terms of code complexities, however, it might come in handy in situations where you want to use a function once and then throw it away after the purpose is served. Also, this method displays how long pieces of codes can be minimized, hence this method makes a worthy entry into the list of our proposed solutions.
valid = lambda age: (age.isdigit() and int(age) > 0 and ( (int(age) >= 18 and "You are an Adult!") or "You are not an Adult")) or \ valid(input( "Invalid input.Please make sure your Age is a valid numerical vaule!\nPlease enter your age: "))
print(valid(input("Please enter your age: ")))
Output:
Please enter your age: -1
Invalid input. Please make sure your Age is a valid numerical vaule!
Please enter your age: 0
Invalid input. Please make sure your Age is a valid numerical vaule!
Please enter your age: twenty five
Invalid input. Please make sure your Age is a valid numerical vaule!
Please enter your age: 25
You are an Adult!
Conclusion
Thus proper validation of user input is of utmost importance for a bug-free code and the methods suggested above might prove to be instrumental in achieving our cause. I prefer the use of PyInputPlus module since defining custom validations might get tedious in case of complex requirements. Also, the use of recursive methods must be avoided unless you are sure about your requirements since they require more memory space and often throw Stack Overflow Exceptions when operations are too large.
I hope you found this article helpful and it helps you to accept valid user inputs with ease. Stay tuned for more interesting stuff in the future!
Where to Go From Here?
Enough theory, let’s get some practice!
To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?
Practice projects is how you sharpen your saw in coding!
Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?
Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.
Do you want to one-linerize the append() method in Python? I feel you—writing short and concise one-liners can be an addiction!
This article will teach you all the ways to append one or more elements to a list in a single line of Python code!
Python List Append
Let’s quickly recap the append method that allows you add an arbitrary element to a given list.
How can you add an elements to a given list? Use the append() method in Python.
Definition and Usage
The list.append(x) method—as the name suggests—appends element x to the end of the list.
Here’s a short example:
>>> l = []
>>> l.append(42)
>>> l
[42]
>>> l.append(21)
>>> l
[42, 21]
In the first line of the example, you create the list l. You then append the integer element 42 to the end of the list. The result is the list with one element [42]. Finally, you append the integer element 21 to the end of that list which results in the list with two elements [42, 21].
Syntax
You can call this method on each list object in Python. Here’s the syntax:
Problem: How can you create a list and append an element to a list using only one line of Python code?
You may find this challenging because you must accomplish two things in one line: (1) creating the list and (2) appending an element to it.
Solution: We use the standard technique to one-linerize each “flat” multi-line code snippet: with the semicolon as a separator between the expressions.
a = [1, 2, 3]; a.append(42); print(a)
This way, we accomplish three things in a single line of Python code:
Creating the list [1, 2, 3] and assigning it to the variable a.
Appending the element 42 to the list referred to by a.
Problem: How can we append multiple elements to a list in a for loop but using only a single line of Python code?
Example: Say, you want to filter a list of words against another list and store the resulting words in a new list using the append() method in a for loop.
# FINXTER TUTORIAL:
# How to filter a list of words? words = ['hi', 'hello', 'Python', 'a', 'the']
stop_words = {'a', 'the'}
filtered_words = [] for word in words: if word not in stop_words: filtered_words.append(word) print(filtered_words)
# ['hi', 'hello', 'Python']
You first create a list of words to be filtered and stored in an initially empty list filtered_words. Second, you create a set of stop words against you want to check the words in the list. Note that it’s far more efficient to use the set data structure for this because checking membership in sets is much faster than checking membership in lists. See this tutorial for a full guide on Python sets.
You now iterate over all elements in the list words and add them to the filtered_words list if they are not in the set stop_words.
Solution: You can one-linerize this filtering process using the following code:
filtered_words = [word for word in words if word not in stop_words]
Here’s the complete code that solves the problem using the one-liner filtering method:
# FINXTER TUTORIAL:
# How to filter a list of words? words = ['hi', 'hello', 'Python', 'a', 'the']
stop_words = {'a', 'the'}
filtered_words = [word for word in words if word not in stop_words] print(filtered_words)
# ['hi', 'hello', 'Python']
Here’s a short tutorial on filtering in case you need more explanations:
In the previous example, you’ve already seen how to use the if statement in the list comprehension statement to append more elements to a list if they full-fill a given condition.
How can you filter a list in Python using an arbitrary condition? The most Pythonic and most performant way is to use list comprehension [x for x in list if condition] to filter all elements from a list.
Try It Yourself:
The most Pythonic way of filtering a list—in my opinion—is the list comprehension statement [x for x in list if condition]. You can replace condition with any function of x you would like to use as a filtering condition.
For example, if you want to filter all elements that are smaller than, say, 10, you’d use the list comprehension statement [x for x in list if x<10] to create a new list with all list elements that are smaller than 10.
Here are three examples of filtering a list:
Get elements smaller than eight: [x for x in lst if x<8].
Get even elements: [x for x in lst if x%2==0].
Get odd elements: [x for x in lst if x%2].
lst = [8, 2, 6, 4, 3, 1] # Filter all elements <8
small = [x for x in lst if x<8]
print(small) # Filter all even elements
even = [x for x in lst if x%2==0]
print(even) # Filter all odd elements
odd = [x for x in lst if x%2]
print(odd)
The output is:
# Elements <8
[2, 6, 4, 3, 1] # Even Elements
[8, 2, 6, 4] # Odd Elements
[3, 1]
This is the most efficient way of filtering a list and it’s also the most Pythonic one. If you look for alternatives though, keep reading because I’ll explain to you each and every nuance of filtering lists in Python in this comprehensive guide.
Python Append One Line to File
Problem: Given a string and a filename. How to write the string into the file with filename using only a single line of Python code?
Example: You have filename 'hello.txt' and you want to write string 'hello world!' into the file.
hi = 'hello world!'
file = 'hello.txt' # Write hi in file '''
# File: 'hello.txt':
hello world! '''
How to achieve this? In this tutorial, you’ll learn four ways of doing it in a single line of code!
Here’s a quick overview in our interactive Python shell:
Exercise: Run the code and check the file 'hello.txt'. How many 'hello worlds!' are there in the file? Change the code so that only one 'hello world!' is in the file!
The most straightforward way is to use the with statement in a single line (without line break).
hi = 'hello world!'
file = 'hello.txt' # Method 1: 'with' statement
with open(file, 'a') as f: f.write(hi) '''
# File: 'hello.txt':
hello world! '''
You use the following steps:
The with environment makes sure that there are no side-effects such as open files.
The open(file, 'a') statement opens the file with filename file and appends the text you write to the contents of the file. You can also use open(file, 'w') to overwrite the existing file content.
The new file returned by the open() statement is named f.
In the with body, you use the statement f.write(string) to write string into the file f. In our example, the string is 'hello world!'.
Of course, a prettier way to write this in two lines would be to use proper indentation:
with open(file, 'a') as f: f.write(hi)
This is the most well-known way to write a string into a file. The big advantage is that you don’t have to close the file—the with environment does it for you! That’s why many coders consider this to be the most Pythonic way.
You can find more ways on my detailed blog article.
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:
• Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.
This article answers a number of questions how to accomplish different things with a Python array in one line. By studying these questions, you’ll become a better coder. So, let’s roll up your sleeves and get started!
Python One Line Print Array
If you just want to know the best way to print an array (list) in Python, here’s the short answer:
Pass a list as an input to the print() function in Python.
Use the asterisk operator * in front of the list to “unpack” the list into the print function.
Use the sep argument to define how to separate two list elements visually.
Here’s the code:
# Create the Python List
lst = [1, 2, 3, 4, 5] # Use three underscores as separator
print(*lst, sep='___')
# 1___2___3___4___5 # Use an arrow as separator
print(*lst, sep='-->')
# 1-->2-->3-->4-->5
Try It Yourself in Our Interactive Code Shell:
This is the best and most Pythonic way to print a Python array list. If you still want to learn about alternatives—and improve your Python skills in the process of doing so—read the following tutorial!
The most basic ternary operatorx if c else y returns expression x if the Boolean expression c evaluates to True. Otherwise, if the expression c evaluates to False, the ternary operator returns the alternative expression y.
Here’s a minimal example:
var = 21 if 3<2 else 42
# var == 42
While you read through the article to boost your one-liner power, you can listen to my detailed video explanation:
Method 1: If the loop body consists of one statement, simply write this statement into the same line: for i in range(10): print(i). This prints the first 10 numbers to the shell (from 0 to 9).
Method 2: If the purpose of the loop is to create a list, use list comprehension instead: squares = [i**2 for i in range(10)]. The code squares the first ten numbers and stores them in the array list squares.
Let’s have a look at both variants in more detail in the following article:
How to iterate over an array in a single line of code?
Say, you’ve given an array (list) lst and you want to iterate over all values and do something with them. You can accomplish this using list comprehension:
lst = [1, 2, 3]
squares = [i**2 for i in lst]
print(squares)
# [1, 4, 9]
You iterate over all values in the array lst and calculate their square numbers. The result is stored in a new array list squares.
You can even print all the squared array values in a single line by creating a dummy array of None values using the print() function in the expression part of the list comprehension statement:
This creates an array of ten elements filled with the value 0. You can also fill the array with other elements by replacing the 0 with the desired element—for example, [None] * 10 creates a list of ten None elements.
Python Initialize Array One Line
There are many ways of creating an array (list) in Python. Let’s get a quick overview in the following table:
Code
Description
[]
Square bracket: Initializes an empty list with zero elements. You can add elements later.
[x1, x2, x3, … ]
List display: Initializes an empty list with elements x1, x2, x3, … For example, [1, 2, 3] creates a list with three integers 1, 2, and 3.
[expr1, expr2, ... ]
List display with expressions: Initializes a list with the result of the expressions expr1, expr2, … For example, [1+1, 2-1] creates the list [2, 1].
[expr for var in iter]
List comprehension: applies the expression expr to each element in an iterable.
list(iterable)
List constructor that takes an iterable as input and returns a new list.
[x1, x2, ...] * n
List multiplication creates a list of n concatenations of the list object. For example [1, 2] * 2 == [1, 2, 1, 2].
You can play with some examples in our interactive Python shell:
How can you filter an array in Python using an arbitrary condition?
The most Pythonic way of filtering an array is the list comprehension statement [x for x in list if condition]. You can replace condition with any function of x you would like to use as a filtering criterion.
For example, if you want to filter all elements that are smaller than, say, 10, you’d use the list comprehension statement [x for x in list if x<10] to create a new list with all list elements that are smaller than 10.
Here are three examples of filtering a list:
Get elements smaller than eight: [x for x in lst if x<8].
Get even elements: [x for x in lst if x%2==0].
Get odd elements: [x for x in lst if x%2].
lst = [8, 2, 6, 4, 3, 1] # Filter all elements <8
small = [x for x in lst if x<8]
print(small) # Filter all even elements
even = [x for x in lst if x%2==0]
print(even) # Filter all odd elements
odd = [x for x in lst if x%2]
print(odd)
The output is:
# Elements <8
[2, 6, 4, 3, 1] # Even Elements
[8, 2, 6, 4] # Odd Elements
[3, 1]
This is the most efficient way of filtering an array and it’s also the most Pythonic one.
Python programmers will improve their computer science skills with these useful one-liners.
Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.
The book’s five chapters cover tips and tricks, regular expressions, machine learning, core data science topics, and useful algorithms. Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments. You’ll also learn how to:
• Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting
By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.