Category

Python

112 guides in this category.

Read A CSV File To List Of Dictionaries In Python

The most common form of data I have played with is generally found in CSV format. This makes the data easy to understand but difficult to modify or change, especially when the CSV file contains lots of columns. In this article I will demonstrate how I frequently use this file format to import it into a useable data structure in Python, namely, a list of Python dictionaries. Let’s start with…

Read guide

Python List Not Appending? Troubleshooting - Solutions for Beginners

Why does a Python list not append an item? When you use the list method .append() to insert a list item to the end of its existing contents, you could be in for a surprise if this doesn’t happen in some instances. The main reasons for why this may occur are due to the improper usage of the list method or adding a variable that doesn’t actually contain the information…

Read guide

2 Ways To Create A Python List With Identical Elements: One-Liners

How can you create a list with identical elements in it with Python? There are two ways to create a list with identical elements in Python. One method is fairly straightforward and easy to remember, whereas the other involves the itertools library. The one I apply the most in my Python coding is the method that uses the asterisk operator to a list containing the item I want to replicate.…

Read guide

Fix NameError: Python List Is Undefined

How do you fix the NameError: Python list is undefined type errors? When you get this error in your Python code there are a few ways to fix the problem and in essence, the easy fix is to check you’re working on a list variable that has been initiated as a list . The three common causes I have found in my own Python code for why this error pops…

Read guide

Python List Not Sorting: Troubleshooting With Examples

Why does a list not sort properly in Python as expected? There are a couple of reasons why a list may not have sorted as expected in Python. Here are a couple of ways to diagnose the problem to help you check. Here’s a quick list (no pun intended!) you can use to quickly check: Are all elements within the list of the same data type? Look at setting them…

Read guide

Python Lists: Order Alphabetically & Sorting Examples

How do you sort a Python list alphabetically? There are two easy ways to sort a list in Python: using the standard sorted() function or using the .sort() list method. Assuming you have a list of strings you can apply either method to sort the list alphabetically. If you have a list of numbers and strings you can use the parameter key to change all values within the list to…

Read guide

List Comprehension In Reverse Order With Python

How do you perform a list comprehension in reverse using Python? A list comprehension is generally a short one line code that allows you to create a new list by iterating through an iterator (such as another list). The syntax for a list comprehension is [expression for variable in iterable if condition] with the if condition part being optional. The easiest way to perform a reverse iteration is to use…

Read guide

How To Remove Leading Zeroes With Python Dates

How do you remove leading zeroes in Python formatted dates? I have been sending data through to a Suitescript API endpoint and have received the error that the date information I am sending through needs to be of the format D/M/YYYY , here’s the error specifically: Currently, the way the date is formatted and sent from my Python code is as follows: The f-string enables me to construct the date…

Read guide

Convert JSON To CSV In Python: Complete Code With Example

How do you convert JSON to CSV using Python quickly and easily? If you’re looking to store data received from an API that responds with JSON data and want to convert this to a CSV file then Python can easily help. Simply import the standard json and csv libraries into your Python code then read the json data into a variable and construct it to a one-dimensional format that can…

Read guide

JSON.dumps Not Able To Serialize Object

If you have tried to serialize an object in Python into JSON you may have come across an oblique error that mentions you’re unable to serialize it, but what does this mean? I recently had an example whereby I needed to transfer a dict object through to an external API endpoint and I thought by simply using the json.dumps() function that I would be able to create a json object…

Read guide

Download Multiple Files On Web Page Using Requests And BeautifulSoup

Ever found yourself scrolling through a web page filled with multiple files, feeling overwhelmed with the tedious process of clicking on each one individually to download them? Wouldn’t it be great to automate this task, saving both time and effort? I had a similar requirement where I needed to download a lot of PDFs on a single web page, and clicking on each, waiting for the PDF to download, and…

Read guide

Can You Download Python for Free? Where and How?

If you are interested in learning Python programming language, you might be wondering whether you can download it for free. The answer is yes , you can download Python for free. Python is an open-source programming language, which means that its source code is freely available and can be modified and distributed by anyone. Python can be downloaded for free from the official Python website, which provides installers for Windows,…

Read guide

Download Files Using Python Requests Library

If you’re looking to download a file using Python, the requests library is a great option to consider. This library allows you to easily make HTTP requests and handle responses in a Pythonic way. First, you’ll need to install the requests library if you haven’t already. You can do this using pip , the package installer for Python. Once you have requests installed, you can use it to make a…

Read guide

Copy List Using [:] In Python

The empty slice operator [:] in Python is a powerful and concise way of copying a list. It is shorthand syntax allowing you to create a new list that contains all the elements of the existing list where the operator is used. This operator is represented by one colon wrapped in square brackets [:] with no values or spaces inside. While the empty slice operator may seem like a simple…

Read guide

Why Does list1 = list2 Not Create A Copy In Python

When starting out in Python it can be easy to think that the expression list2 = list1 will make list2 contain a copy of list1 . But it doesn’t take long to realise that this doesn’t meet expectations of what actually happens in the wild. Take the following code as an example: Huh? Why did list2 contain the same contents as list1 even when the insertion of additional elements in…

Read guide

id() Function in Python: What’s It Good For?

The id() function in Python is a built-in function that returns the unique identity of an object. This identity is an integer that is guaranteed to be unique and constant for the object during its lifetime . The id() function can be used to determine whether two variables refer to the same object in memory . This is helpful when determining the type of copy you have with two variables:…

Read guide

How To Remove From String In Python

How do you remove a newline character \n from a string in Python? The easiest way to remove a new line from a string in Python is by using the string method .replace() . Another way is to use the string method .strip() if the new line is at the start or end of the string. Here are some examples demonstrating how to remove the new line characters: As you…

Read guide

Close Python In Terminal: Command & Shortcut

How do you quit out of Python when you’re in an interactive shell environment? The easiest way to close the Python shell in Terminal is to issue the quit() command. Here’s an example demonstrating how to exit from a terminal window using the a-Shell app on the iPhone: Use the exit() command As you can see from the example above I was able to access the Python interactive shell by…

Read guide

Python: Move Files From One Directory To Another

How do you move files from one directory to another using Python? If you want to move specific files from one directory to another with Python, use the glob library to fetch the correct files, then use the os library’s rename method to change the current file to the new directory. Here is an example of how this might look using a Python script. With the current code I have…

Read guide

Effortlessly Increment Your File Names with Python (Free Code)

How do you create a file name with an incrementing number in Python? To create an incrementing file name in Python, run a while loop that checks the existence of a file, and if it exists, use Regex to modify the file name by replacing the integer at the end of the file with the next number. Continue looping until the file name does not exist in the destination folder.…

Read guide

How To Format Time In 24-Hours Using Python (Examples)

How do you format time to be in 24-hours using Python? In Python you can format a datetime object to be displayed in 24-hour time using the format %H:%M . This is not to be confused with the 12-hour time which uses the format %I:%M and may have %p appended to the end to denote AM/PM . Here’s an example demonstrating the conversion of time from 12-hour format to a…

Read guide

How To Format HH:MM AM/PM Time To 24 Hours In Python (Examples)

How do you format a string in the format of HH:MM AM/PM to 24-hour time in Python? To change a string in the format HH:MM AM/PM to 24-hour time in Python use the datetime.datetime.strptime(original string, format string) function located in the datetime library. As the datetime class needs to be imported from the datetime library you need to make sure you include the reference twice, otherwise you may get strptime…

Read guide

Convert DD/MM/YY To Date In Python (Examples)

How do you convert a string in the format of DD/MM/YY to a date in Python? To convert a string in the format of DD/MM/YY to a date in Python import the datetime library and use the datetime.datetime.strptime(date string, format string) function (yes, that is not a typo the datetime library has a datetime class and it contains the strptime function). To make it easier to access the strptime() function…

Read guide

How To Find The Difference Between Two Or More Sets In Python

How can you find the difference between two sets in Python? In Python, you can find the difference between two sets using the .difference() method. The set and frozenset objects contain a built-in method labelled difference() which helps to find the non-matching elements in the source object not found in the other sets passed in to the .difference( others) parameter. Here is an example demonstrating how to find the difference…

Read guide

Python Ceiling Function: What Is It And How Does It Work?

What is the ceiling function in Python, and how does it work? The ceiling function in Python is found in the math library and it’s method name is ceil() which takes a sole numeric parameter. To use the ceiling function in Python you will need to import the math library, like so: As you can see from the above Python REPL code the output produces the greatest integer. If the…

Read guide

Download Images Using Selenium Python With Full Code Examples

How do you download images using Selenium Python? Selenium provides a way to create a screenshot of your browser’s view using the .save screenshot(file name) method, but this will take a photo of the viewport – what if you just want to download the image as it is ? Unfortunately, Selenium doesn’t have the capability of selecting menu items in your browser window, therefore you will need to install a…

Read guide

Python: Sort List Of Tuples By First Element In 10 Seconds

How do you sort a list of tuples by the first element in each tuple in Python? To sort a list of tuples in Python use the .sort() list method if you want to modify the list to sort or the sorted() function if you want to generate a new list. Use the parameter key with either function and set the value of that parameter to a lambda expression that…

Read guide

What Does AttributeError: Module datetime Has No Attribute strptime Mean?

What does AttributeError: module 'datetime' has no attribute 'strptime' mean and how can you easily fix it? When parsing a string and transforming that to a date you can make use of the function strptime in the datetime module. To use this function simply import datetime as you normally would with any module, and use the function as follows: Notice in the above code that the function strptime is found…

Read guide

NetSuite RESTlet Example (OAuth1): Send File Using Python

How do you send a file through to your NetSuite instance via a RESTlet using a Python Script? If you know how to send a POST request through to a RESTlet using Python then only minor modifications need to be made to enable the sending of a file. One reason why you may prefer sending a file for NetSuite process is where you have a lot of data to consume…

Read guide

NetSuite RESTlet Example (OAuth1): Python Script To RESTlet

How do you send data to your NetSuite RESTlet using Python? To send data to your NetSuite RESTlet using Python code utilise the handy requests oauthlib library. If you need to upload a series of CSV files and want to perform some data cleaning before being uploaded and want to avoid the Import CSV process then you can create a simple RESTlet and insert your clean data directly. Create Your…

Read guide

How To Remove Trailing Slash In Python

How do you remove a trailing slash in a string using Python? There are two popular ways to remove a trailing slash from a string in Python. The most common approach is to use the .rstrip() string method which will remove all consecutive trailing slashes at the end of a string. If you only need to remove one trailing slash the string slice operator can be another alternative. Here’s how…

Read guide

Python Int Function: How It Works And Why You May Need To Create Your Own

How does the int() function work I. Python and could you write your own function? The int(x, base=10) function in Python takes two parameters: the first parameter x being either a number or string and the second representing the base number to return ( 10 being default which represents the decimal number system) and converts x into a whole integer number. A simple example of converting a string is demonstrated…

Read guide

How To Read File Into List With 1 Line Of Code In Python

How do read the contents of a file in Python and insert these lines into a list? Using the built-in function open() and the asterisk operator a file’s contents can easily be translated into a list with the following one-liner: [ open('my file.txt')] . What Does open() Function Do? The built-in open() function has one required parameter and several optional parameters. The required parameter is the location of the file.…

Read guide

Change List Elements To Int In Python: 1 Line Of Code

How do you convert a list of strings to a list of integers in Python? And can you do it with one line of code? To convert a list of strings to a list of integers use the built-in map() function if you know the contents of the original list will all convert to integers, otherwise use a lambda function in your map() , or use a list comprehension with…

Read guide

Range And Len Functions Together In Python

How do you find the length of a range object in Python? In Python the built-in function len() can provide the length of a string or list, can the same function be used to count the length of a range object too? What Is A Range Object? A range object is one of the three basic sequence types in Python alongside tuples and lists. The built-in function range(start, stop[, step])…

Read guide

5 String Operators In Python Everyone Needs To Know

What are the most common string operators used in Python and why they’re essential to know? It doesn’t take long when you begin programming in Python to work with strings and to start modifying these strings by using common operators. Here I’ll look at 5 of the most common string operators I use in my own Python code and how you can use them in your own code. String Concatenation…

Read guide

How To Remove File Extension From Path String In Python: One-Liner

How do you remove the file extension from a path in Python? And can you do it using just one line of code? The file extension is generally the last set of characters after the final period in a path string. Removing the file extension helps with trying to either rename the file name or with renaming the file extension. For example, if my full path string to a particular…

Read guide

What Does [:-1] In Python Mean And Why Use It?

What does [:-1] in Python actually do and why would you want to use it? [:-1] in Python is a slice operation used on strings or lists and captures all contents of the string or list except for the last character or element . Here are some examples demonstrating the operation of this code with strings: As you can see from the simple code example above a variable my string…

Read guide

** In Python In 2 Minutes With Code Examples

What operator is used to raise a number to a power in Python? In Python the double asterisk operator is used to help calculate the exponent of a number raised to a power. This is done without a need to import the Python math library. For example, 2 to the power of 3 can be expressed using the double asterisk operator 2 3 , here the resulting output with the…

Read guide

What Does Colon Equals Mean In Python? The New Walrus Operator :=

In Python 3.8 a new assignment expression hit allowing for easier access of variables that are used when being assigned. Here are some tips on how this can be used in your everyday coding. Wait, what’s an assignment expression ? You may have heard of the term assignment operator and seen its use in the wild when doing things like incrementing a variable by 1 in Python. This is where…

Read guide

How To Zip Two Or Multiple Lists Together In Python

How do you zip two lists together in Python? What if you want to zip multiple lists together, is it the same process or something different? The built-in function zip() allows users to combine iterables, such as a list, into tuples by taking each corresponding item from the lists passed into its parameters merging the lists into one. It does not matter whether you have two or multiple lists the…

Read guide

Python Initialize Dictionary: Use Dict Constructor Or Dict Literal?

How do you initialize an empty dictionary in Python? Is it best to use dict() or {} ? There are two common ways of initializing a dictionary in Python. One involves using the built-in function dict() and is known as the dict constructor , whereas the other method is known as dict literal and has the syntax {} . Here’s an example demonstrating how to initialize using both approaches in…

Read guide

How To Increment By 2 Or More In For Loop In Python [Examples]

How do you increment through a for loop by 2 or more using Python? To iterate by 2 or more when processing a for loop expression use the third parameter of the range(start, stop, step) built-in function, or if using the slice operator use the third parameter. Here is an example demonstrating how to iterate through a for-loop in Python using the range() function. As you can see from the…

Read guide

Check Phone Numbers Using Regex In Python [Examples]

How can you use the Python Regex library to check if a string represents a phone number? To check if a string matches a specific pattern use the Regex library’s match or exec methods. Before writing your Regex pattern inspect the variants for the phone number field to see whether you’re Regex pattern will match. For example, if upon your inspection you find the following variants: By noting all the…

Read guide

Convert Percentage String To Decimal Like 30% To 0.3 In Python

How do you convert a string representing a percentage number into an actual number that can be used to perform calculations? To convert a string represented as a percentage number into an actual decimal number in Python use the built-in float() function after removing the percent symbol from the string and any other characters that prevent numeric conversion. Without purging from the original string the percent symbol you will get…

Read guide

How To Capitalize First Letter Of Every Word In Python (One-Liner)

How do you capitalize the first letter of each word in a string using Python? To capitalize the first letter of every word in Python using one line of code enter the following: " ".join([x.capitalize() for x in my string.split()]) . Here is an example demonstrating how the code works in the Python REPL: As you can see from the above example the output produces a string with each character…

Read guide

How To Find The Length Of A String In Python Using Len

How do you find the length of the string in Python without importing any libraries? To find the length of a string in Python use the built-in len() function, which takes one parameter that can be of data type string, bytes, tuple, list, range, or a collection (such as a dictionary, set, or frozen set). The len() function, when used on a string, will return the number of characters in…

Read guide

Does Python Have Ternary Operator?

Does Python have a ternary operator? If so, how does it work? A ternary operator, otherwise known as a conditional expression, is a simple if-else statement that is performed on one line of code to evaluate a condition. The value entered before the if clause is the True value returned, whereas the value after the else clause is the False value returned. The expression between the if and the else…

Read guide

What Is The Difference Between AND And OR In Python?

What is the difference between using the logical operators and and or in Python? When using the and logical operator in Python all conditions in the statement need to be True for the entire expression to evaluate to True . If one condition evaluates to False then the entire expression evaluates to False . When using the or logical operator only one condition in the entire expression needs to evaluate…

Read guide

How To Split A String In Half In Python: 1 Line Of Code

How do you split a string into two equal halves using Python? To tackle this exercise you need to know how you’re going to operate on odd numbered string lengths. For example, how would you like your code to operate on the string halve . As it has 5 characters you’re going to have 5 possible solutions: hal and ve OR ha and lve ha, l and ve halve OR…

Read guide

What Does Double Slash Operation // Do In Python?

What is the double slash operator and what does the double slash operator // do in Python? The double slash operator in Python returns the quotient value from a division operation. The operator requires two numbers: a dividend and a divisor, which are the same numbers used with standard division operations in mathematics. For example, the mathematical expression 75 ÷ 10 has the 75 as the dividend, 10 as the…

Read guide

Square A Number In Python Without Importing Math Library

How do you square a number in Python, and how do you check if a number is a square using Python? To square a number in Python use the power operator followed by the number 2. For example, to square the number 9 simply write 9 2 . Here’s an example demonstrating the use of this operator when squaring a number: Wait! I thought squaring a negative number produces a…

Read guide

Square Root In Python Without Importing Math Library

How do you find the square root of a number in Python? Can you find the square root without needing to import the math library? The most common approach in calculating the square root of a number in Python is to import the math library and use the method math.sqrt(n) where n is the number you want to square root. But there is an even easier way of being able…

Read guide

Find Duplicates In List: Python One Liner

How do you find all the duplicates from a list in Python? To find all the duplicate elements from a list using Python, use the following list comprehension: The result from the above code will be a list of unique elements representing all the duplicate elements from the original list. Here’s an example of how this looks in your Python console: Get List Of Duplicates What if you want a…

Read guide

Python Code To Remove Duplicates From List - 1 Liner

How do you remove duplicates from a list using Python? To remove duplicate elements from a list in Python use a list comprehension to create a new list with no duplicates with this code: [x for idx, x in enumerate(original list) if x not in original list[idx+1:]] Here is an example demonstrating how this code works: As you can see from the example above the result from the list comprehension…

Read guide

Python ++ How To Increment A Variable (Code Examples)

How do you increment an integer variable in Python? Many other languages use the double plus sign operator on the variable to increment by 1, but what is Python’s plus plus operator equivalent? Python does not yet (as of version 3.9) have the ++ operator. Instead to increment an integer variable in Python by 1 use the operator assignment syntax i += 1. Is There A ++ In Python? As…

Read guide

How To Check If A Number In Python Is Even Or Odd

How can you tell if a number is odd or even in Python? The easiest way to determine if a number is even or odd in Python is to use the modulus operator . This operator, denoted as the percentage sign % displays the remainder from a division operation. To determine if a number is even simply apply my number % 2 == 0 where my number is your number…

Read guide

How To Find Most Frequent Element In List In Python (Code Examples, No Import Statements)

How do you find the most common element in a list using Python without importing any special libraries? To find the most frequent elements in a list iterate through the list and store the frequency of each element into a dictionary with the key representing the element and the value representing the frequency. Finally, sort the dictionary by value in descending order to see the results with the highest frequency…

Read guide

How To Quickly Check Python Version In PyCharm

How can you check the version of Python you are using in PyCharm? There are three ways to check the version of your Python interpreter being used in PyCharm: 1. check in the Settings section; 2. open a terminal prompt in your PyCharm project; 3. open the Python Console window in your Python project. Let’s look at each of these in a little more detail: How To Check Python Version…

Read guide

What Does [:] Mean In Python? Code Examples

The slice operator enables you to capture a subset of data from an original list or string using the format [start:stop:step] . Some popular use cases where I have used the slice operator include: Extracting year and/or month and/or day of the month from a string Extracting the zip code at the tail end of an address string Masking bank account or credit card numbers Extracting area code from phone…

Read guide

How To Print A String And A Variable In Python (3 Techniques)

There are times when you want to be able to print the contents of a variable along with a string to help provide some context around what has been output to the console. So how can you print both a string and a variable in Python? The three methods of being able to print a string and a variable together in Python is by using: string concatenation (using + ),…

Read guide

Python Lower: Examples

How do you get a string to be all lowercase in Python? Thankfully there’s a built-in method that doesn’t require importing any external libraries to get a string to lower case, here’s how you do it. To get a string to all lowercase, use the built-in string method .lower() , which turns all characters in the string variable to lower case. Here is an example demonstrating the transformation of a…

Read guide

How To Get First Character From String (Shortest Code And Examples)

Is there a quick and easy way to get the first character from a string in Python? Yes, there is using the slice operator. To get the first character in a string simply use the code my string[0] where my\ string is a variable containing the string and the slice operator [0] captures the first index of that string, being the first character. Index numbers start at 0 from the…

Read guide

How To Get Last Character From A String (Shortest Code Examples)

How do you get the last character from a string using Python? Thankfully Python has an easy way to fetch the last character from a string using the slice operator . To get the last character of the string in Python use the syntax my string[-1] . The square brackets are used to indicate a specific character by index number, and as string data types can be iterated, you can…

Read guide

How To Remove First & Last Characters From String In Python (Code Examples)

How can you remove the first and last characters from a string easily in Python? Can it be done using just one line of code? To remove the first and last characters from a string in Python use the slice operator on the string to return the needed characters, for example, my string[1:-1] . Here is an example demonstrating the technique: Slice Notation: How Does It Work? The powerful slice…

Read guide

How To Add An Empty Element To A List In Python

To insert or append an empty element into a Python list you need to first define what is meant by the word empty . By empty do you mean an empty string, None or something else? While I may use None in this post you can easily substitute it for something else according to your requirements. To add an empty element into a list either replace the existing element with…

Read guide

How To Check If List Is Empty In Python

Similar to the previous post on how to check if a string is empty the same principles and methods apply when checking if a list is empty in Python. To check if a list is empty either use the direct approach by using an expression where a list is compared to an empty list or use the boolean expression with a not operator (i.e. if not my empty list: )…

Read guide

Check Empty String Python - 3 Unique Approaches

How can you check if a string is empty in Python? To determine if a string is empty in Python use of the following three means available: see if the string has any length by using the built-in len() function, do a direct comparison using the expression == "" or convert the string to a boolean data type and if the result is false it is an empty string. Let’s…

Read guide

How To Change A String To Lower Case In Python

A way to easily sort a list of strings equally is to change all the strings to lower case, but how do you change strings to lower case in Python? To change a string to lower case in Python use the string method .lower() like this: my string.lower() . Similarly, to change a string to upper case in Python use the string method .upper() like this: my string.upper() . An…

Read guide

Sort Dict By Value Or Sort Dict By Key In Python: 1 Liners

It can be easy to sort a list, whether a list of strings or even a list of dictionaries, but can you sort a dictionary? One way to sort a dictionary by the values of each key : value pair in Python is to use a dictionary comprehension . Dictionary comprehensions are very similar to list comprehensions and have the following schema: The first expression within the dictionary comprehension, the…

Read guide

Python ord() Function (Code Examples)

What does the ord() function do? The built-in ord() function in Python converts any Unicode character into a number. It only takes one parameter which must be a single Unicode character, any more than one character produces an error. An example of the type of error you will get when sending more than 1 Unicode character is demonstrated here: Notice how Python informs us of what is expected – a…

Read guide

List Length In Python: Using len() Function

To find the length of a list use the built-in len() function which takes a single parameter that is iterable. For example this could be a string, list, tuple or dictionary and here is how it would look: This may be the easiest and quickest way of being able to find the length of a list and other data types, but what if you want to exclude certain items from…

Read guide

How To Use NOT Operator In IF Statement In Python [Code Examples]

One way to determine if one value does not equal another is to use the != comparator, but what if you’re not comparing two values – how can you determine if something is not true? Python has an inbuilt operator aptly called not which permits a user to check a variable, or a function’s result to test if the variable or returned value is not valid. Some classic use cases…

Read guide

Enumerate Dictionary In Python: Video Demonstration

Previously I looked at how to use the enumerate() built-in function with a for loop to provide two variables when iterating through a list. In that article the enumerate() function provides both an index number and the element in each list by wrapping these together into a tuple. But what happens when the enumerate() function is applied to a dictionary? As done previously let’s inspect the output of the enumerated…

Read guide

How To Use 2 Variables In For Loop In Python (Code Examples)

The for loop in Python allows the user to iterate through a variable that is iterable , such as a list. In Python the syntax for the loop is simply: for x in my list: and you’re off looping through each element in my list . But how do you access the index number of the element? In other programming languages, such as JavaScript, looping involves just the index number:…

Read guide

How To Print A List In Python (And With Custom Formatting)

When you want to print the contents of a list you have a couple of different options depending upon the context. If you’re in the REPL there’s the easy method of entering the name of the variable storing the list, to the option of using the standard print function. If you’re within a script file the best option would be to use the print function, or if you want to…

Read guide

Python Increment By 1

How do you increase a variable by one in Python? In other popular programming languages to increment a variable by one you can use the simple increment syntax of ++ , for example i++ will make the value of i increase by 1 , but how do you do this in Python? To increment a variable in Python use the syntax += 1 , for example to increment the variable…

Read guide

Transpose A List Of Lists: Python Examples, No Imports

When using a spreadsheet it can be as easy as using the TRANSPOSE function on a range to transform the rows and columns into columns and rows, but how do you do that in Python? To transpose a list of lists in Python first flatten the two-dimensional list into a one-dimensional list then use the following: [flat list[e::len(list 2d[0])] for e in range(len(list 2d[0]))] where flat list represents the flattened…

Read guide

Sort List By String Length: Python Code Examples (No Imports)

To sort a list of strings according to their length, use a lambda function on the key parameter with the lambda function using the len function on each element. This is represented as follows using the sorted function: sorted(my list, key=lambda el: len(el)) . Here is a simple example demonstrating the use of this code: Or, if using the .sort() list method would be represented as follows: What if after…

Read guide

Python: Empty String To INT

To convert a string to an integer you use the handy int() function. For example, if you have a string such as "79" and you insert this like so into the int() function: int("79") you get the result 79 . But what happens when you don’t have a string that easily converts into a number? Here are some examples where converting a string into an integer type simply will not…

Read guide

How To Flatten A List Of Lists In Python (Examples & No Imports)

Recently, I had an exercise where I needed to flatten a two-dimensional list down to just one dimension, something where I needed the result to be like this: There were a couple of ways I completed this task, one involved using the common for-loop process but as a one-liner, another involved using a standard Python function, and the third way introduced me to the concept of recursion in Python .…

Read guide

Is A List A Data Type?

In Python there is a handy function to determine the data type of any variable, and it is aptly called type() . This function can help to assess whether a variable is of a certain data type to help you perform any type of computation on it. The different data types available in Python are: int , float , str , dict , list , and tuple . Therefore, list…

Read guide

Python For Loop One Liner With IF Conditions [Code Examples]

There have been times when I wanted to perform a simple for-loop filter operation on a list, and I’ve often wondered if there’s a quick and simple way to do this without having to import any libraries. What I discovered is that there was an easy way, and what’s awesome about it is that it can be done in one simple line! If you’ve been operating with dictionaries or lists,…

Read guide

Python: Get Average Of Two Dimensional List - No Imports [Code Examples]

In my previous article where I found the average of a list in Python without using imports, in this article I want to expand how you could apply the same concept, but to two-dimensional lists. Thankfully, if you know how to find the average of a one dimensional list in Python, you can simply expand this knowledge to finding the average of a two-dimensional list. The big question to ask,…

Read guide

How To Sort 2D Array In Python: 1 Line Of Code Without Numpy

How do you sort a two-dimensional array in Python easily without importing libraries? Thankfully, some native functions in Python make sorting arrays a breeze. I recently had a project where I had the following data structures, representing each unpaid invoice by the customer, the days they were overdue and how much was outstanding. Here’s a simplified sample of the data I was working with (the first row contains the name…

Read guide

Python: Average Of List Of Numbers - Without Imports [One-Liner]

How do you calculate the simple average of a list of numbers in Python, without needing to import any libraries? Unfortunately, there’s no native average or avg function in Python to easily calculate the average of a list containing just numbers: To calculate the average of a list of numbers in Python, use the sum function and the len function and divide the total sum by the total length of…

Read guide

Check For Word In String: Python 1 Liner

How can you check if a word is found in a string using Python? Recently, I had an issue where I wanted to exclude strings from a list if they contained a certain word. I thought I could use the following common code familiar to most using Python: But the problem ended up being a little more difficult than that. For example, what if you want to exclude the term…

Read guide

Sort List Of Dictionaries By Key: Python 1 Liner

How can you sort a list of dictionaries by a key contained in each dictionary using Python? Can you do it in 1 line to show off your friends? Of course! To sort a list of dictionaries use the sorted() function with the key parameter set to a lambda function that uses the common key found in each dictionary that you want to sort the list by. Previously I posted…

Read guide

Python: Sort List From Second (or Nth Index) On

How do you sort a list by the second (or nth) element on in Python? How can you leave the first or nth elements in a list as they are but then have the remaining elements in the list sorted? When applying the .sort() list method on a list Python will sort all elements in that list, but what if you only wanted to sort after a certain index number?…

Read guide

Reverse Order Of List In Python Without For Loops (Examples, One-Liners, No Imports)

There have been times when after creating a list in Python I’ve wanted to sort a list and then have the list reversed from ascending to descending. To reverse the order of a list in Python use either the .reverse() list method which mutates the original list, or the slice operator technique [::-1] which returns a new list. What are the quickest ways to get this task done? Here are…

Read guide

How To Remove Characters From A String In Python (Examples, No Imports)

There are three main ways within Python on how to remove specific characters from a string in Python, and I’ve clustered these approaches based on the following methods: Built-in string methods By pattern By position Each approach has its own unique way of being able to perform the task required, so we will explore each with the use of examples to illustrate what might suit your use case best. Remove…

Read guide

Create A Dictionary In Python: Quick 5 Minute Beginners Guide

How do you create a dictionary in Python? Dictionaries in Python are mutable data types that contain key: value pairs. A dictionary can be a great way to organise information, especially if checks need to be performed prior for uniqueness and/or the value of that key needs to be changed, skipped or inserted. Creating A Dictionary Dictionaries can be created using either the dict() constructor method, using the dict literal…

Read guide

List Changes Unexpectedly In Python: How Can You Stop It?

Why is it when you copy a list in Python doing b list = a list that, any changes made to a list or to b list modify the other list? If you’ve played with lists in Python you will reach a point where you want to copy a list to make modifications to it without changing the original list. Initially you would think the following would work: As you…

Read guide

Sort Nested Dictionary By Key Or By Value In Python: One Liner

How do you sort a nested dictionary in Python by key or by value? Throughout this article, I will use the following example, which displays a nested dictionary that contains three main properties labelled dict1 , dict2 , dict3 and from each key they reference another dictionary which contains a simple dictionary of three keys labelled A , B and C with each key matched to the same value 1…

Read guide