-2.9 C
New York
Wednesday, February 1, 2023

10 Useful Python One-Liners You Must Know – Make Tech Easier

Dark mode:

Write concise, eloquent Python code with this guide.
Although it’s pushed well past the 30-year mark since its release, Python remains one of the most relevant high-level programming languages in existence. Many developers will opt to use this language to make applications that can easily be maintained and require minimal hand-holding to work in a number of operating systems and distributions of Linux.
One of the greatest benefits of Python is its ability to snake (pun completely intended) around a lot of conventions found in other languages with little effort on behalf of the programmer, letting you compose incredibly simple little “quips” to get the job done. Here are a few examples!
Also read:How to Utilize Python for Basic Linux System Administration and Networking Tasks
Because you don’t have to deal with tedious things like addresses in memory, swapping your variables for each other can be done in one simple line:
Just separate each variable with a comma, and swap them around!
This is what the concept would look like in a snippet:
Running this in console should output “4 1”.
Python’s math tools allow for some very creative code to perform otherwise complex calculations. For example, what’s the quickest way to find the number of ways a number of objects can be arranged? Do a factorial. With the reduce() call, you can quickly come up with the answer!
This call will calculate the factorial of any number you previously define in “x.”
Don’t forget that reduce() is a component of Python’s functools library. This is what the code looks like in a snippet:
Your console should output 479001600 from this particular calculation. Go ahead and make “x” whatever you want!
Also read:How to Run a Python Script on Mac
Python’s syntax rules allow you to do pretty wild things. For instance, initialize and declare as many variables as you want in one single go. This as opposed to doing so line-by-line.
Print these out and you’ll end up with “16 78 195.” The neat thing is that you don’t even have to restrict yourself to declaring one type of variable within a line. Replace the “y” declaration with a string like “Hi” and it’ll be just fine!
Python requires you to iterate through a file line-by-line as you would in many other languages. Even so, it gives you the ability to implement the entirety of the function of both opening and reading the file into one single line of code:
Now, if I want to just display the text of my own default bash configuration file, this is what I’d write:
Also read:How to Pretty Print a JSON File in Python
Just like with reading a file, the process of writing to one is pretty straightforward in this nifty language.
The with statement within Python lets you avoid the hassle of having to close the file handle. Hence it won’t conflict with other applications that would attempt to access it while yours is open.
You can now use the one-liner you learned for reading a file to check whether that line was added correctly!
Similarly to how other scripting languages like LUA work, Python lets you spawn pre-populated lists as long as the operations lead to a predictable result. In this snippet, we create a list of 10 integers ranging from 0 to 9:
Printing this list will yield a comma-separated list of numbers with the parameters we discussed earlier.
Also read:Python range() Explained: What It Is and How to Use It
Ever wonder how many user names there actually are in your particular Linux installation? Python has a great way of doing this in a single line by opening your “/etc/passwd” file. All we have to do in this case is trim out everything from the first colon (“:”) in each line onwards.
If you haven’t sniffed around in that file, you may be surprised to find that there are many more users created by your system than the one you log in with and the root user.
User lists are normally this long because the system creates its own forms of authentication based on services you run.
Like any self-respecting language, Python lets you randomize things, but it can’t help but take things a step further and let you do so to generate a password in one single line. It is admittedly a very long one..
This particular snippet will generate a 32-character password that allows for spaces. Adjust to your liking. If you don’t want a space in the password for whatever reason, remove the space within the string declaration. Don’t forget to import the “random” library or else your code won’t work!
Also read:Python While Loop: Intro and Explanation
If you’re reading a longer file and you’re trying to find how many instances of a particular expression exist within it, there’s a little zinger for that:
In this particular example, we’re trying to find how many times the letter “d” appears in the string following it. By printing the output, the console lets us know there are 3 instances of the letter. You can do this with entire words and search within a file.
With a little bit of iterative magic, it’s possible to convert hexadecimal code into plain text in one simple expression:
The large pile of gibberish within iter() is a hexadecimal expression that this code converts to read out to, “Wow, I’m writing in hexadecimal!”
Also read:How to Create an SSH Honeypot to Catch Hackers in Your Linux Server
While it does have some flaws particular to some coding styles, Python offers a much more beginner-friendly atmosphere than other languages due to its flexibility with variable types. It’s an interpreted language, so it doesn’t need you to deal with the tedium of allocating memory by hand and ensuring that it’s freed when no longer in use.
Python’s developers are strongly against the idea of invalidating old code with new releases, and have been historically very careful to ensure backwards compatibility with much older code. In 2005, the Python community had to deal with a difficult issue as reduce() and a number of other functions were removed from the standard library and had to be imported from another one as of Python 3000. In general, these things are announced and if your code stops running properly, the console provides helpful information that lets you find out why and make adjustments accordingly.
If you want to use an integrated development environment for Python, there are a few options for you that work across operating systems:
Image credit: Pixabay All screenshots by Miguel Leiva-Gomez
Our latest tutorials delivered straight to your inbox
How to Install macOS in VirtualBox
How to Fix 'No SIM Card Detected' Error on Android and iPhone
How to Convert Legacy BIOS to UEFI in Windows
How to Copy and Paste Text, Files and Folders in Linux Terminal
How to Access an Android Phone With a Broken Screen
How to Bypass Paywalls of Leading News Websites
7 Useful Cron Alternatives For Linux
Free Tools to Check SD Card Speed and Capacity
11 Common ADB Commands You Should Know
Safari Not Working on Your iPhone? Here's How to Fix It
Affiliate Disclosure: Make Tech Easier may earn commission on products purchased through our links, which supports the work we do for our readers.
© 2022 Uqnic Network Pte Ltd.
All rights reserved.


Related Articles


Please enter your comment!
Please enter your name here

Latest Articles