To check if a file exists in an AWS S3 bucket, the easiest way is with a try/except block and using the boto3 get_object() function. import boto3 s3c = boto3.client('s3', region_name="us-east-2",aws_access_key_id="YOUR AWS_ACCESS_KEY_ID",aws_secret_access_key="YOUR AWS_SECRET_ACCESS_KEY") try: obj = s3c.get_object(Bucket="YOUR-BUCKET",Key="FILENAME") result = obj["Body"].read() except s3c.exceptions.NoSuchKey: #File doesn't exist pass When working with files in your programs, sometimes you […]
Python
How to Write CSV File to AWS S3 Bucket Using Python
To write a pickle file from an AWS S3 Bucket using Python and pandas, you can use the boto3 package to access the S3 bucket. After accessing the S3 bucket, you need to create a file buffer with the io BytesIO() function. Then, write the pickle file to the file buffer with the pandas to_csv() […]
How to Write Excel File to AWS S3 Bucket Using Python
To write an Excel file to an AWS S3 Bucket using Python and pandas, you can use the boto3 package to access the S3 bucket. After accessing the S3 bucket, you need to create a file buffer with the io BytesIO() function. Then, write the pickle file to the file buffer with the pandas to_excel() […]
How to Write Pickle File to AWS S3 Bucket Using Python
To write a pickle file to an AWS S3 Bucket using Python and pandas, you can use the boto3 package to access the S3 bucket. After accessing the S3 bucket, you need to create a file buffer with the io BytesIO() function. Then, write the pickle file to the file buffer with the pandas to_pickle() […]
How to Read Excel File from AWS S3 Bucket Using Python
To read an Excel file from an AWS S3 Bucket using Python and pandas, you can use the boto3 package to access the S3 bucket. After accessing the S3 bucket, you can use the get_object() method to get the file by its name. Finally, you can use the pandas read_excel() function on the Bytes representation […]
How to Read CSV File from AWS S3 Bucket Using Python
To read a CSV file from an AWS S3 Bucket using Python and pandas, you can use the boto3 package to access the S3 bucket. After accessing the S3 bucket, you can use the get_object() method to get the file by its name. Finally, you can use the pandas read_csv() function on the Bytes representation […]
How to Read Pickle File from AWS S3 Bucket Using Python
To read a pickle file from ab AWS S3 Bucket using Python and pandas, you can use the boto3 package to access the S3 bucket. After accessing the S3 bucket, you can use the get_object() method to get the file by its name. Finally, you can use the pandas read_pickle() function on the Bytes representation […]
How to Convert pandas Column dtype from Object to Category
To convert a column in a pandas DataFrame from a column with data type “object” to a column with data type “category”, use the astype() function. import pandas as pd df = pd.DataFrame({ "column": ["a","b","c","a","b","c","b","d"] }) print(df["column"].dtype) df["column"] = df["column"].astype('category') print(df["column"].dtype) #Output: object category When working with different types of data in pandas, the ability […]
How to Group By Columns and Find Standard Deviation in pandas
To group by multiple columns and then find the standard deviation of rows in a pandas DataFrame, you can use the groupby() and std() functions. import pandas as pd df = pd.DataFrame({"animal_type":["dog","cat","dog","cat","dog","dog","cat","cat","dog"], "gender":["F","F","F","F","M","M","M","F","M"], "age":[1,2,3,4,5,6,7,8,9], "weight":[10,20,15,20,25,10,15,30,40]}) print(df) print(df.groupby(["animal_type","gender"])["age"].std().rename('age_standard_deviation').reset_index()) #Output: animal_type gender age weight 0 dog F 1 10 1 cat F 2 20 2 dog F […]
How to Group By Columns and Find Variance in pandas
To group by multiple columns and then find the variance of rows in a pandas DataFrame, you can use the groupby() and var() functions. import pandas as pd df = pd.DataFrame({"animal_type":["dog","cat","dog","cat","dog","dog","cat","cat","dog"], "gender":["F","F","F","F","M","M","M","F","M"], "age":[1,2,3,4,5,6,7,8,9], "weight":[10,20,15,20,25,10,15,30,40]}) print(df) print(df.groupby(["animal_type","gender"])["age"].var().rename('age_variance').reset_index()) #Output: animal_type gender age weight 0 dog F 1 10 1 cat F 2 20 2 dog F 3 […]
How to Filter pandas DataFrame by Date
To filter a pandas DataFrame by date, you can use both basic comparisons with strings representing the date you want to filter by. import pandas as pd df = pd.DataFrame({ "date": ["2021-09-30", "2021-12-31", "2022-03-31", "2022-06-30", "2022-09-30", "2022-12-31"], "sales": [100,30,50,60,10,80] }) df["date"] = pd.to_datetime(df["date"]) df_2022 = df[df["date"] > "2021-12-31"] print(df_2022) #Output: date sales 2 2022-03-31 50 […]
Using pandas to_csv() Function to Append to Existing CSV File
To append to an existing CSV file with pandas, you can use the to_csv() function and pass “mode=’a’” to specify you want to append to the CSV file. df.to_csv('example.csv', mode='a', index=False, header=False) When outputting data to different types of files, the ability to append to a file easily is valuable. One such case is if […]
Using GroupBy() to Group Pandas DataFrame by Multiple Columns
To group a pandas DataFrame by multiple columns, you can use the groupby() function and pass a list of column names to group by. import pandas as pd df = pd.DataFrame({"animal_type":["dog","cat","dog","cat","dog","dog","cat","cat","dog"], "gender":["F","F","F","F","M","M","M","F","M"], "age":[1,2,3,4,5,6,7,8,9], "weight":[10,20,15,20,25,10,15,30,40]}) print(df) print(df.groupby(["animal_type","gender"]) #Output: animal_type gender age weight 0 dog F 1 10 1 cat F 2 20 2 dog F 3 […]
Get Day of Year from Date in pandas DataFrame
To extract the day of year from a datetime column in pandas, you can access the “day_of_year” property. The “day_of_year” property returns a 64-bit integer. import pandas as pd df = pd.DataFrame({ "date": ["2021-09-30", "2021-12-31", "2022-03-31", "2022-06-30", "2022-09-30", "2022-12-31"], "sales": [100,30,50,60,10,80] }) df["date"] = pd.to_datetime(df["date"]) df["day_of_year"] = df["date"].dt.day_of_year print(df) #Output: date sales day_of_year 0 2021-09-30 […]
Get Days in Month from Date in pandas DataFrame
To extract the days in month from a datetime column in pandas, you can access the “days_in_month” property. The “days_in_month” property returns a 64-bit integer. import pandas as pd df = pd.DataFrame({ "date": ["2021-09-30", "2021-12-31", "2022-03-31", "2022-06-30", "2022-09-30", "2022-12-31"], "sales": [100,30,50,60,10,80] }) df["date"] = pd.to_datetime(df["date"]) df["days_in_month"] = df["date"].dt.days_in_month print(df) #Output: date sales days_in_month 0 2021-09-30 […]
Get Quarter from Date in pandas DataFrame
To extract the quarter from a datetime column in pandas, you can access the “quarter” property. The “quarter” property returns a 64-bit integer. import pandas as pd df = pd.DataFrame({ "date": ["2021-09-30", "2021-12-31", "2022-03-31", "2022-06-30", "2022-09-30", "2022-12-31"], "sales": [100,30,50,60,10,80] }) df["date"] = pd.to_datetime(df["date"]) df["quarter"] = df["date"].dt.quarter print(df) #Output: date sales quarter 0 2021-09-30 100 3 […]
Convert String to Datetime in pandas with pd.to_datetime()
To convert a column of strings representing dates to a column of datetimes in pandas, you can use the pd.to_datetime() function. import pandas as pd df = pd.DataFrame({ "date": ["2021-09-30", "2021-12-31", "2022-03-31", "2022-06-30", "2022-09-30", "2022-12-31"] }) df["date"] = pd.to_datetime(df["date"]) print(df["date"]) #Output: 0 2021-09-30 1 2021-12-31 2 2022-03-31 3 2022-06-30 4 2022-09-30 5 2022-12-31 Name: date, […]
Get Day Name from Datetime in pandas DataFrame
To extract the day name from a datetime column in pandas, you can use the day_name() function. day_name() returns a string with the name of the day of a datetime. import pandas as pd df = pd.DataFrame({ "date": ["2021-09-30", "2021-12-31", "2022-03-31", "2022-06-30", "2022-09-30", "2022-12-31"], "sales": [100,30,50,60,10,80] }) df["date"] = pd.to_datetime(df["date"]) df["day_name"] = df["date"].dt.day_name() print(df) #Output: […]
Get Day of Week from Datetime in pandas DataFrame
To extract the day of the week from a datetime column in pandas, you can access the “dayofweek” property. The “dayofweek” property returns a 64-bit integer between 0 and 6, where 0 represents Monday and 6 represents Sunday. import pandas as pd df = pd.DataFrame({ "date": ["2021-09-30", "2021-12-31", "2022-03-31", "2022-06-30", "2022-09-30", "2022-12-31"], "sales": [100,30,50,60,10,80] }) […]
Get Month Name from Datetime in pandas DataFrame
To get the month name from a datetime column in pandas, you can use the pandas month_name() function. month_name() returns the name of the month as a string. import pandas as pd df = pd.DataFrame({ "date": ["2021-09-30", "2021-12-31", "2022-03-31", "2022-06-30", "2022-09-30", "2022-12-31"], "sales": [100,30,50,60,10,80] }) df["date"] = pd.to_datetime(df["date"]) df["month_name"] = df["date"].dt.month_name() print(df) #Output: date sales […]
Get Month from Datetime in pandas DataFrame
To extract the month from a datetime column in pandas, you can access the “month” property. The “month” property returns a 64-bit integer. import pandas as pd df = pd.DataFrame({ "date": ["2021-09-30", "2021-12-31", "2022-03-31", "2022-06-30", "2022-09-30", "2022-12-31"], "sales": [100,30,50,60,10,80] }) df["date"] = pd.to_datetime(df["date"]) df["month"] = df["date"].dt.month print(df) #Output: date sales month 0 2021-09-30 100 9 […]
Get Year from Date in pandas DataFrame
To extract the year from a datetime column in pandas, you can access the “year” property. The “year” property returns a 64-bit integer. import pandas as pd df = pd.DataFrame({ "date": ["2021-09-30", "2021-12-31", "2022-03-31", "2022-06-30", "2022-09-30", "2022-12-31"], "sales": [100,30,50,60,10,80] }) df["date"] = pd.to_datetime(df["date"]) df["year"] = df["date"].dt.year print(df) #Output: date sales year 0 2021-09-30 100 2021 […]
Get Year from Date in Python
When using Python, there are a number of ways to extract the year from a date in Python. The easiest way to get the year from a date is to access the “year” attribute of a date or datetime object. from datetime import datetime currentDateTime = datetime.now() print(currentDateTime.year) #Output: 2022 You can also use the […]
Drop First n Rows of pandas DataFrame
To drop the first n rows of a pandas DataFrame, the easiest way is with iloc. import pandas as pd df = pd.DataFrame({'Name': ['Jim', 'Sally', 'Bob', 'Sue', 'Jill', 'Larry'], 'Weight': [130.54, 160.20, 209.45, 150.35, 117.73, 187.52], 'Height': [50.10, 68.94, 71.42, 48.56, 59.37, 63.42], 'Age': [43,23,71,49,52,37] }) print(df) print(df.iloc[3:]) #Output: Name Weight Height Age 0 Jim […]
Drop Last n Rows of pandas DataFrame
To drop the last row of a pandas DataFrame, the easiest way is with the iloc. import pandas as pd df = pd.DataFrame({'Name': ['Jim', 'Sally', 'Bob', 'Sue', 'Jill', 'Larry'], 'Weight': [130.54, 160.20, 209.45, 150.35, 117.73, 187.52], 'Height': [50.10, 68.94, 71.42, 48.56, 59.37, 63.42], 'Age': [43,23,71,49,52,37] }) print(df) print(df.iloc[:-3]) #Output: Name Weight Height Age 0 Jim […]
Drop First Row of pandas DataFrame
To drop the first row of a pandas DataFrame, the easiest way is with the iloc. import pandas as pd df = pd.DataFrame({'Name': ['Jim', 'Sally', 'Bob', 'Sue', 'Jill', 'Larry'], 'Weight': [130.54, 160.20, 209.45, 150.35, 117.73, 187.52], 'Height': [50.10, 68.94, 71.42, 48.56, 59.37, 63.42], 'Age': [43,23,71,49,52,37] }) print(df) print(df.iloc[1:]) #Output: Name Weight Height Age 0 Jim […]
Drop Last Row of pandas DataFrame
To drop the last row of a pandas DataFrame, the easiest way is with the iloc. import pandas as pd df = pd.DataFrame({'Name': ['Jim', 'Sally', 'Bob', 'Sue', 'Jill', 'Larry'], 'Weight': [130.54, 160.20, 209.45, 150.35, 117.73, 187.52], 'Height': [50.10, 68.94, 71.42, 48.56, 59.37, 63.42], 'Age': [43,23,71,49,52,37] }) print(df) print(df.iloc[:-1]) #Output: Name Weight Height Age 0 Jim […]
Convert pandas Series to Dictionary in Python
To convert a pandas Series to a dictionary in Python, the easiest way by using to_dict() on a pandas Series. import pandas as pd df = pd.DataFrame({"animal_type":["dog","cat","dog","cat","dog","dog","cat","cat","dog"], "gender":["F","F","F","F","M","M","M","F","M"], "age":[1,2,3,4,5,6,7,8,9], "weight":[10,20,15,20,25,10,15,30,40]}) animal_types = df["animal_type"].to_dict() print(animal_types) #Output: {0: 'dog', 1: 'cat', 2: 'dog', 3: 'cat', 4: 'dog', 5: 'dog', 6: 'cat', 7: 'cat', 8: 'dog'} If you […]
Convert pandas Series to List in Python
To convert a pandas Series to a list in Python, the easiest way by using values.tolist() on a pandas Series. import pandas as pd df = pd.DataFrame({"animal_type":["dog","cat","dog","cat","dog","dog","cat","cat","dog"], "gender":["F","F","F","F","M","M","M","F","M"], "age":[1,2,3,4,5,6,7,8,9], "weight":[10,20,15,20,25,10,15,30,40]}) animal_types = df["animal_type"].values.tolist() print(animal_types) #Output: ['dog', 'cat', 'dog', 'cat', 'dog', 'dog', 'cat', 'cat', 'dog'] You can also use list() function to convert a pandas Series […]
Get pandas Index Values as List in Python
To get the index of a pandas DataFrame and create a list in Python, the easiest way by using index.to_list() on a DataFrame. import pandas as pd df = pd.DataFrame({"animal_type":["dog","cat","dog","cat","dog","dog","cat","cat","dog"], "gender":["F","F","F","F","M","M","M","F","M"], "age":[1,2,3,4,5,6,7,8,9], "weight":[10,20,15,20,25,10,15,30,40]}) index_list = df.index.to_list() print(index_list) #Output: [0, 1, 2, 3, 4, 5, 6, 7, 8] You can also use index.values.tolist() function to convert […]
Python to_bytes() – Create Bytes Object from Integer
The Python int to_bytes() function allows you to convert integers into an array of bytes representing that integer. num = 5 num_bytes = num.to_bytes(3, byteorder="big") print(num_bytes) print(type(num_bytes)) #Output: b'\x05' <class 'bytes'> When working with different types of objects when programming, the ability to easily be able to convert a variable into a variable of another […]
Convert Integer to Bytes in Python
To convert an integer to bytes in Python, you can use the Python int to_bytes() function. to_bytes converts an int object into an array of bytes representing that integer. num = 10 num_bytes = num.to_bytes(3, byteorder="big") print(num_bytes) #Output: b'\x00\x00\n' When working with different types of objects when programming, the ability to easily be able to […]
Using Python To Split String by Comma into List
To split a string by comma in Python, you can use the Python string split() function and pass ‘,’ to get a list of strings. string = "This,is,a,string,with,commas" print(string.split(",")) #Output: ['This', 'is', 'a', 'string', 'with', 'commas'] You can also use the split() function from the re (regular expression) module. import re string = "This,is,a,string,with,commas" print(re.split(",", […]
How to Group By Columns and Find Minimum in pandas DataFrame
To group by multiple columns and then find the minimum of values by group in a pandas DataFrame, you can use the groupby() and min() functions. import pandas as pd df = pd.DataFrame({"animal_type":["dog","cat","dog","cat","dog","dog","cat","cat","dog"], "gender":["F","F","F","F","M","M","M","F","M"], "age":[1,2,3,4,5,6,7,8,9], "weight":[10,20,15,20,25,10,15,30,40]}) print(df) print(df.groupby(["animal_type","gender"])["age"].min().rename('age_min').reset_index()) #Output: animal_type gender age weight 0 dog F 1 10 1 cat F 2 20 2 dog […]
How to Group By Columns and Find Maximum in pandas DataFrame
To group by multiple columns and then find the maximum of values by group in a pandas DataFrame, you can use the groupby() and max() functions. import pandas as pd df = pd.DataFrame({"animal_type":["dog","cat","dog","cat","dog","dog","cat","cat","dog"], "gender":["F","F","F","F","M","M","M","F","M"], "age":[1,2,3,4,5,6,7,8,9], "weight":[10,20,15,20,25,10,15,30,40]}) print(df) print(df.groupby(["animal_type","gender"])["age"].max().rename('age_max').reset_index()) #Output: animal_type gender age weight 0 dog F 1 10 1 cat F 2 20 2 dog […]
How to Group By Columns and Find Sum in pandas DataFrame
To group by multiple columns and then find the sum of rows in a pandas DataFrame, you can use the groupby() and sum() functions. import pandas as pd df = pd.DataFrame({"animal_type":["dog","cat","dog","cat","dog","dog","cat","cat","dog"], "gender":["F","F","F","F","M","M","M","F","M"], "age":[1,2,3,4,5,6,7,8,9], "weight":[10,20,15,20,25,10,15,30,40]}) print(df) print(df.groupby(["animal_type","gender"])["age"].sum().rename('age_sum').reset_index()) #Output: animal_type gender age weight 0 dog F 1 10 1 cat F 2 20 2 dog F 3 […]
Get pandas Column Names as List in Python
To get the column names of a pandas DataFrame and create a list in Python, the easiest way by using columns.to_list() on a DataFrame. import pandas as pd df = pd.DataFrame({"a":[1],"b":[2],"c":[3],"d":[4]}) columns = df.columns.to_list() print(columns) #Output: ["a","b","c","d"] You can also use the Python list() function to get DataFrame column names as a list. import pandas […]
How to Group By Columns and Find Mean in pandas DataFrame
To group by multiple columns and then find the mean of rows in a pandas DataFrame, you can use the groupby() and mean() functions. import pandas as pd df = pd.DataFrame({"animal_type":["dog","cat","dog","cat","dog","dog","cat","cat","dog"], "gender":["F","F","F","F","M","M","M","F","M"], "age":[1,2,3,4,5,6,7,8,9], "weight":[10,20,15,20,25,10,15,30,40]}) print(df) print(df.groupby(["animal_type","gender"])["age"].mean().rename('age_mean').reset_index()) #Output: animal_type gender age weight 0 dog F 1 10 1 cat F 2 20 2 dog F 3 […]
How to Group By Columns and Count Rows in pandas DataFrame
To group by multiple columns and then find the count of rows in a pandas DataFrame, you can use the groupby() and count() functions. import pandas as pd df = pd.DataFrame({"animal_type":["dog","cat","dog","cat","dog","dog","cat","cat","dog"], "gender":["F","F","F","F","M","M","M","F","M"]}) print(df) print(df.groupby(["animal_type","gender"])["gender"].count().rename('count').reset_index()) #Output: animal_type gender 0 dog F 1 cat F 2 dog F 3 cat F 4 dog M 5 dog M […]
Using Python to Find Maximum Value in List
To get the maximum of a list in Python, we can use the Python max() function. You can use the max() function in Python to get the maximum value of a list of numbers, strings and objects. list_of_numbers = [10,32,98,38,47,34] print(max(list_of_numbers)) #Output 98 When working with different collections of data in Python, the ability to […]
Using Python to Find Minimum Value in List
To get the minimum of a list in Python, we can use the Python min() function. You can use the min() function in Python to get the minimum value of a list of numbers, strings and objects. list_of_numbers = [10,32,98,38,47,34] print(min(list_of_numbers)) #Output 10 When working with different collections of data in Python, the ability to […]
Change Column Name in pandas DataFrame
To change a column’s name in a pandas DataFrame in Python, the easiest way is that you can use the pandas rename() function. import pandas as pd df = pd.DataFrame({"some_column": [1, 2, 3]}) print(df) df.rename(columns={"some_column": "changed_name"}, inplace=True) print(df) #Output: some_column 0 1 1 2 2 3 changed_name 0 1 1 2 2 3 When working […]
numpy pi – Get Value of pi Using numpy Module in Python
To get the value of pi when using the numpy module in Python, you can use the pi constant. import numpy as np print(np.pi) #Output: 3.141592653589793 When working with different programming languages, the ability to use different mathematical constants easily is very useful for a number of different reasons. The ability to be able to […]
Split Column by Delimiter in pandas DataFrame
To split a column by delimiter when using pandas in Python, you can use the pandas str.split() function. import pandas as pd df = pd.DataFrame({"name":["Bob Smith","Penny Johnson","Lorenzo Diaz","Juan Perez","Maria Rizzo"]}) df[["first_name","last_name"]] = df["name"].str.split(" ",expand=True) print(df) #Output: name first_name last_name 0 Bob Smith Bob Smith 1 Penny Johnson Penny Johnson 2 Lorenzo Diaz Lorenzo Diaz 3 […]
Count Unique Values in pandas DataFrame
To count the unique values of columns in a pandas DataFrame or unique values of a Series, the simplest way is to use the pandas nunique() function. unique_values = df["variable"].nunique() When working with data, it’s important to be able to find the basic descriptive statistics of a set of data. One such piece of information […]
Using Python to Get Day of Week
To get the day of the week in Python, the easiest way is to use the datetime weekday() function. weekday() returns a number between 0 and 6 where 0 represents Monday and 6 represents Sunday. from datetime import datetime now = datetime.now() day_of_week = now.weekday() print(now) print(day_of_week) #Output: 2022-10-07 08:46:25.705684 4 Another way you can […]
How to Measure Execution Time of Program in Python
To measure the execution time of a program in Python, use the time module to find the starting time and ending time. After you have the starting time and ending time, subtract the two times. import time starting_time = time.time() print("Process started…") print("Process ended…") ending_time = time.time() print(ending_time – starting_time) #Output: 0.0018320083618164062 When creating Python […]
How to Create Block and Multi-Line Comments in Python
To create a block comment in Python, you just need to add # before each line – just like you would for a regular single line comment. # This is a valid block comment # Here is some more commentary # And finally some more information You can also use triple quotes to create multi-line […]
Get Substring from String in Python with String Slicing
To get a substring of a string variable in Python, you can use string slicing and specify the start point and end point of your substring. string = "example" print(string[0]) #first character print(string[:4]) #first 4 characters print(string[1:4]) #characters 2-4 print(string[2:]) #all characters after the 2nd character print(string[-2:]) #last two characters print(string[:-2]) #all characters until the […]
Python isdigit() Function – Check if Characters in String are Digits
The Python string isdigit() function checks if all characters in a string are digits and returns a boolean value. s1 = "123" s2 = "hello" print(s1.isdigit()) print(s2.isdigit()) #Output: True False When working with strings in Python, the ability to make checks and determine certain properties easily is very valuable. One such case is if you […]
Subtract Seconds from Datetime Variable Using Python timedelta() Function
To subtract seconds from a datetime using Python, the easiest way is to use the Python timedelta() function from the datetime module. from datetime import timedelta, datetime now = datetime.now() one_second_in_past = now – timedelta(seconds=1) sixty_seconds_in_past = now – timedelta(seconds=60) one_hour_in_past = now – timedelta(seconds=3600) print(now) print(one_second_in_past) print(sixty_seconds_in_past) print(one_hour_in_past) #Output: 2022-09-29 15:45:53.655282 2022-09-29 15:45:52.655282 2022-09-29 […]
Replace Forwardslashes in String Using Python
To replace forwardslashes in a string with Python, the easiest way is to use the Python built-in string replace() function. string_with_forwardslashes = "This/is/a/string/with/forwardslashes." string_with_underscores = string_with_forwardslashes.replace("/","_") print(string_with_underscores) #Output: This_is_a_string_with_forwardslashes. When working with strings in Python, being able to manipulate your variables easily is important. There are a number of built in string methods which allow […]
How to Divide Two Numbers in Python
To divide two numbers in Python, you can use the division operator /. You can divide integers, floats, and decimal variables. a = 1 b = 2 c = a / b print(c) #Output: 0.5 One of the most fundamental operations in programming is performing different calculations and math. You can easily divide two numbers […]
How to Multiply Two Numbers in Python
To multiply two numbers in Python, you can use the multiplication operator *. You can multiply integers, floats, and decimal variables. a = 1 b = 2 c = a * b print(c) #Output: 2 One of the most fundamental operations in programming is performing different calculations and math. You can easily multiply two numbers […]
How to Subtract Two Numbers in Python
To subtract two numbers in Python, you can use the subtraction operator –. You can subtract integers, floats, and decimal variables. a = 1 b = 2 c = a – b print(c) #Output: -1 One of the most fundamental operations in programming is performing different calculations and math. You can easily subtract two numbers […]
How to Add Two Numbers in Python
To add two numbers in Python, you can use the addition operator +. You can add integers, floats, and decimal variables. a = 1 b = 2 c = a + b print(c) #Output: 3 One of the most fundamental operations in programming is performing different calculations and math. You can easily add two numbers […]
Not Equal Operator != in Python
You can check if an object is not equal to another object in Python with the not equal operator !=. a = 0 b = 1 if a != b: print("a is not equal to b") #Output: a is not equal to b When working with objects and variables in Python, the ability to check […]
Python Check if Dictionary Value is Empty
To check if a dictionary value is empty in Python, you can use the len() function and check if the length of the value is 0. d = {"a":[]} if len(d["a"]) == 0): print("value 'a' is empty") #Output value 'a' is empty When working with different collections of data in programming, the ability to perform […]
Python Decrement Counter with -= Decrement Operator
To decrement a counter in Python, you can use the -= decrement operator and subtract a number from the counter. i = 0 i -= 1 print(i) #Output: -1 The decrement operator is the equivalent of subtracting a number via simple subtraction. i = 0 i = i – 1 print(i) #Output: -1 In Python, […]
Python Increment Counter with += Increment Operator
To increment a counter in Python, you can use the += increment operator and add a number to the counter. i = 0 i += 1 print(i) #Output: 1 The increment operator is the equivalent of adding a number via simple addition. i = 0 i = i + 1 print(i) #Output: 1 In Python, […]
Python Try Until Success with Loop or Recursion
To try until success in Python, the easiest way is to use a while loop. def someFunction(): return someResult() while True: try: result = someFunction() break except Exception: continue You can also create a recursive function which will call the function if there is an error. def someFunction(): try: result = someResult() return result except […]
Using Python to Get All Combinations of Two Lists
In Python, we can get all combinations of two lists easily. The easiest way to obtain all combinations of two lists is with list comprehension. list1 = ["a", "b", "c"] list2 = [1, 2, 3] combinations = [(x,y) for x in list1 for y in list2] print(combinations) #Output: [('a', 1), ('a', 2), ('a', 3), ('b', […]
What is the Correct File Extension for Python Files?
When creating programs and code in Python, the correct file extension for your code is .py. There are a few other file extensions associated with Python files. In this article, we will discuss the four different Python file types and the file extensions for each of these file types. File Extension for Python Source Code […]
Using Python to Check if Queue is Empty
Using Python to check if a queue is empty is easy. If you are using deque from the collections module, you can use the len() function to get the size of your queue and check if the size is equal to 0. from collections import deque q = deque() if len(q) == 0: print("q is […]
Python not in – Check if Value is Not Included in Object
You can use the not and in operators in Python to check if a value is not included in objects such as lists, dictionaries, sets, tuples, etc. x = "something" l = ["this","is","a","list"] d = {"a":1,"b":2,"c":3} t = (0, 1, 2) s = {0, 1, 2} st = "string" print(x not in l) print(x not […]
Using Python to Check If Variable is Not None
To check if a variable is not None, you can use the inequality operator != and check if the variable is not equal to None. a = None b = "Not None" if a != None: print("a is not None") if b != None: print("b is not None") #Output: b is not None You can […]
Check if Variable is None in Python
To check if a variable is equal to None, you can use the equality operator == and check if the variable is equal to None. a = None b = "Not None" print(a == None) print(b == None) #Output: True False You can also use the is keyword to check if a variable is None. […]
Remove Empty Lists from List in Python
To remove empty lists from a list using Python, the easiest way is to use list comprehension. lst = [1,2,3, [], 0, "a", [], [], "b"] list_without_empty_list = [x for x in lst if x != []] print(list_without_empty_list) #Output: [1, 2, 3, 0, 'a', 'b'] You can also use the Python filter() function. lst = […]
What Curly Brackets Used for in Python
In Python, there are a few uses of curly brackets. The most common use of curly brackets is to define a dictionary. d = { "a":1, "b":2 } print(type(d)) #Output: <class 'dict'> You can also use curly brackets to create a non-empty set. s = {1, 2, 3} print(type(s)) #Output: <class 'set'> One last common […]
Get Username in Python using os module
To get the current username in Python, the easiest way is with the os module getlogin() function. import os print(os.getlogin()) #Output: The Programming Expert Another way you can get the current username is from the dictionary of environment variables of the operating system. import os print(os.environ.get("USERNAME")) #Output: The Programming Expert One other way you can […]
Using Python to Iterate Over Two Lists
To iterate over two lists in Python, you can use the zip() function and a for loop. lst_1 = [0, 1, 2] lst_2 = ["a", "b", "c"] for x, y in zip(lst_1, lst_2): print(x, y) #Output: 0 a 1 b 2 c If you have lists which don’t have the same length, you can use […]
Using Python to Print Variable Type
To print the variable type of a variable in Python, you can use the type() function to get the type and print it with print(). a = 1 b = "string" c = [0, 1, 2] d = (0, 1, 2) e = {"key":"value"} f = 1.0 g = {"set"} print(type(a)) print(type(b)) print(type(c)) print(type(d)) print(type(e)) […]
Sum Columns Dynamically with pandas in Python
To sum columns dynamically, you can create a list containing the columns you want and use the sum() function, passing “axis=1”. import pandas as pd df = pd.read_csv("some_data.csv") cols_to_sum = ["col1","col2"] df["Total"] = df[cols_to_sum].sum(axis=1) When working with collections of data, the ability to aggregate different pieces of data in different ways easily is valuable. One […]
Backwards for Loop in Python
To loop backwards in Python with a for loop, the easiest way is to use the range() function and pass ‘-1’ for the step argument. lst = [0, 1, 2, 3] for i in range(3, -1, -1): print(lst[i]) #Output: 3 2 1 0 If you want to iterate over an iterable object, you can use […]
Remove Character from String in Python by Index
To remove a specific character from a string given a specified index, the easiest way is with string slicing. string = "example string" def remove_char_by_index(s, idx): return s[:idx-1] + s[idx:] print(remove_char_by_index(string,4)) #Output: exaple string When working with strings, the ability to easily manipulate and change the value of your variables is valuable. One such case […]
Using Python to Convert Timestamp to Date
To convert a timestamp to a date in Python, the easiest way is to use the datetime fromtimestamp() function to create a datetime object and then convert that to a date. from datetime import datetime ts = 1661540168 dt = datetime.fromtimestamp(ts).date() print(dt) #Output: 2022-08-26 When working with date and times, the ability to change between […]
Calculate Standard Deviation of List of Numbers in Python
To get the standard deviation of a list in Python, you can create your own function which will apply the standard deviation formula. lst = [0, 3, 6, 5, 3, 9, 6, 2, 1] def standard_dev(l): mean = sum(l) / len(l) return (sum([((x – mean) ** 2) for x in l]) / len(l)) ** 0.5 […]
Using Python to Convert Decimal to String
To convert a decimal to a string in Python, you can use the Python str() function. from decimal import Decimal d = Decimal("1.23") s = str(d) print(d, type(d)) print(s, type(s)) #Output: 1.23 <class 'decimal.Decimal'> 1.23 <class 'str'> When working with different variables in Python, the ability to easily be able to convert a variable into […]
Using Python to Convert Float to Int
To convert a float to an integer in Python, the easiest way is with the int() function. int() will remove the decimal from the floating point number. f = 1.2345 print(int(f)) #Output: 1 You can also use the math module trunc() function to convert a float variable to an integer. import math f = 1.2345 […]
Using Python to Convert Tuple to String
To convert a tuple to a string in Python, the easiest way is with the Python string join() function. t = ('a','b','c','d','e') s = ''.join(t) print(s) #Output: abcde You can also use a for loop to convert a tuple into a string. t = ('a','b','c','d','e') s = "" for item in t: s = s […]
Using Python to Insert Item Into List
To insert an item into a list in Python, you can use the list insert() function. Pass the index and an object to insert to insert() to insert an object at a certain position. lst = [0, 2, 4] lst.insert(2, 3) print(lst) #Output: [0, 2, 3, 4] When working with collections of data, the ability […]
Using Python to Flatten Array of Arrays
To flatten a list of lists in Python, the easiest way is to use list comprehension. list_of_lists = [[1], [2, 3], [4, 5, 6]] flattened_list = [value for sub_list in list_of_lists for value in sub_list] print(flattened_list) #Output: [1, 2, 3, 4, 5, 6] If you have a list of lists which also contain lists of […]
Convert String to Boolean Value in Python
To convert a string variable to a boolean value in Python, you can use the Python bool() function. Non-empty strings are converted to True and empty strings are converted to False. string = "This is a string" empty_string = "" print(bool(string)) print(bool(empty_string)) #Output: True False If you just want to check if a string is […]
How to Check If Value is in List Using Python
To check if a value is in a list using Python, the easiest way is with the in operator. value = 1 l = [0, 1, 2, 3, 4] if value in l: print("value is in list") else: print("value is not in list") #Output: value is in list When working with collections of data in […]
Remove Substring from String in Python with replace()
To remove a specific substring in a string variable in Python, the easiest way is to use the Python string replace() function. s = "This is a string." string_without_substring = s.replace("is","") print(string_without_substring) #Output: This a string. When working with strings in Python, being able to manipulate your variables easily is important. There are a number […]
How to Remove All Punctuation from String in Python
To remove all punctuation from a string in Python, the easiest way is with the Python string translate() function. import string s = "this#&*! is a *(*#string &!#@…'';[with punctuation!|}{" print(s.translate(str.maketrans("","",string.punctuation))) #Output: this is a string with punctuation Another way to remove all punctuation from a string is with a loop and the string replace() function. […]
How to Remove All Spaces from String in Python
To remove all spaces from a string in Python, the easiest way is with the Python string replace() function. string = "This is a string with spaces." print(string.replace(" ","")) #Output: Thisisastringwithspaces. One other easy way to remove all spaces from a string is with regex and the re module. import re string = "This is […]
How to Write Python Dictionary to File
To write a dictionary to a file in Python, there are a few ways you can do it depending on how you want the dictionary written. If you want to write a dictionary just as you’d see it if you printed it to the console, you can convert the dictionary to a string and output […]
Using Python to Add String to List
To add a string to a list in Python, the easiest way is to use the Python list append() function. string = "string" lst = ["a", "b", "c"] lst.append(string) print(lst) #Output: ["a", "b", "c", "string"] You can also wrap a string in square brackets and use the concatenation operator + to add a string to […]
Examples of Recursion in Python
You can use recursion in Python to solve many different problems. In this article, we are going to share with you a few Python recursion examples for you to learn how to use recursion in Python. To use recursion, we need to define a base case for our recursive function and define the recursive step […]
for char in string – How to Loop Over Characters of String in Python
To loop over the characters of a string in Python, you can use a for loop and loop over each character in the following way. string = "example" for char in string: print(char) #Output: e x a m p l e When working with strings, the ability to work with the characters individually is valuable. […]
How to Filter Lists in Python
To filter a list in Python, the easiest way is with list comprehension. lst = [0, 1, 2, 3, 4, 5] filtered = [x for x in lst if x < 2] print(filtered) #Output: [0, 1] You can also use the Python filter() function with a lambda expression. lst = [0, 1, 2, 3, 4, […]
Create Empty File with Python
To create an empty file in Python, you can open a file in write mode and then use the pass keyword to not write anything to the file. with open('example.txt','w') as file: pass If you want to create empty files with different file types, then the method will be different. A shorter solution to above […]
Get Days of timedelta Object in Python
To get the days of a timedelta object in Python, we can use the days property of a timedelta object. import datetime datetime1 = datetime.datetime(2022,8,17,0,0,0) datetime2 = datetime.datetime(2022,8,19,0,0,0) timedelta_object = datetime2 – datetime1 print(timedelta_object.days) #Output: 2 Another solution might be to just look at the date portions of the datetime objects before creating the timedelta […]
Get Python Dictionary Keys as List
To get the values of a dictionary in a list in Python, you can use the dictionary values() function and convert it to a list with list(). d = {"a":3, "b": 5, "c":1, "d":2} list_of_dict_keys = list(d.keys()) print(list_of_dict_keys) #Output: [3, 5, 1, 2] When working with dictionaries, the ability to get information about the keys […]
Get Python Dictionary Values as List
To get the values of a dictionary in a list in Python, you can use the dictionary values() function and convert it to a list with list(). d = {"a":3, "b": 5, "c":1, "d":2} list_of_dict_values = list(d.values()) print(list_of_dict_values) #Output: [3, 5, 1, 2] When working with dictionaries, the ability to get information about the keys […]
Using Python to Calculate Average of List of Numbers
To calculate the average of a list of numbers in Python, the easiest way is to divide the sum of the list by the length of the list with the sum() and len() functions. l = [1,2,3,4,5,6,7] print(sum(l)/len(l)) #Output: 4 You can also use the mean() function from the statistics module to get the average […]
Using Python to Calculate Sum of List of Numbers
To calculate the sum of a list of numbers in Python, the easiest way is with the sum() function. l = [1,2,3,4,5,6,7] print(sum(l)) #Output: 28 You can also use a for loop to sum the numbers of a list. l = [1,2,3,4,5,6,7] s = 0 for num in l: s = s + num print(s) […]
Convert String to List Using Python
To convert a string into a list using Python, the easiest way is with the list() function. string = "string" l = list(string) print(l) #Output: ['s', 't', 'r', 'i', 'n', 'g'] If you want to convert a string into a list of elements with a delimiter, you can use the split() function. string = "this […]
Replace Character in String in Python
To replace a character in a string with another character in Python, you can use the string replace() function. example_string = "This is a string." string_with_i_replaced_with_e = example_string .replace("i","e") print(string_with_i_replaced_with_e) #Output: Thes es a streng. When working with strings in Python, being able to manipulate your variables easily is important. There are a number of […]
Using Python to Add Items to Set
In Python, to add to a set, you can use the add() function. add() will add an element to the set if the element is not already in the set. s = {1, 2, 3} s.add(4) print(s) #Output: {1, 2, 3, 4} You can also use the update() function to add multiple elements from a […]
Check if pandas DataFrame is Empty in Python
There are a few ways you can check if a DataFrame is empty. The easiest way to check if a pandas DataFrame is empty is with the empty property. import pandas as pd empty_dataframe = pd.DataFrame() print(empty_dataframe.empty) #Output: True You can also check if a DataFrame is empty by checking if the length is 0 […]
Using Python to Create Empty DataFrame with pandas
To create an empty DataFrame with pandas in Python, you can use the DataFrame() function. import pandas as pd empty_dataframe = pd.DataFrame() print(empty_dataframe) #Output: Empty DataFrame Columns: [] Index: [] When working with the pandas in Python, the main data structure which is the DataFrame. Depending on the program you are designing, you might need […]
Get Current Datetime in Python
To get the current datetime in Python, you can use the datetime module and datetime.now() function which returns the date and time. import datetime currentDateTime = datetime.datetime.now() print(currentDateTime) #Output: 2022-08-19 08:33:11.283729 If you want to get the current date, then you can convert the datetime to a date with date(). import datetime currentDateTime = datetime.datetime.now() […]
Return Multiple Values from Function in Python
To return multiple values from a function in Python, you can use the return keyword and separate the values by commas. To access the returned values, use tuple unpacking. def function_return_multiple(): return 0, 1, 2, 3 a, b, c, d = function_return_multiple() print(a) print(b) print(c) print(d) #Output: 0 1 2 3 You can also return […]
Using Python to Return Two Values from Function
To return two values from a function in Python, you can use the return keyword and separate the values by commas. To access the two returned values, use tuple unpacking. def function_return_two(): return 0, 1 a, b = function_return_two() print(a) print(b) #Output: 0 1 You can also return two values as a list and then […]
Check if Variable is String in Python
To check if a variable is a string, you can use the type() function and check if the variable is of type string. t = "string" a = 1 l = [0, 1, 2] print(type(t) == str) print(type(a) == str) print(type(l) == str) #Output: True False False You can also use the isinstance() function to […]
Convert Set to List in Python
In Python, the easiest way to convert a set to a list is using the Python list() function. s = {0,1,2,3} converted_to_list = list(s) print(converted_to_list) #Output: [0,1,2,3] When working with collections of items in Python, it can be easier to convert them to other data structures to be able to work more efficiently. We can […]
How to Combine Dictionaries in Python
There are a few ways you can combine dictionaries in Python. The easiest way to merge and combine the keys and values of multiple dictionaries is with the | merge operator. This works with Python 3.9+. d1 = {'apples': 1, 'bananas': 2} d2 = {'oranges': 3, 'pears': 4} d3 = d1| d2 print(d3) #Output: {'apples': […]
Add Key Value Pair to Dictionary in Python
When working with dictionaries in Python, to add a key value pair to a dictionary, you just need to access the key and assign the value. dictionary = {"bananas":4, "pears":5} dictionary["apples"] = 6 print(dictionary) #Output: {"apples":6, "bananas":4, "pears":5} In Python, dictionaries are a collection of key value pairs separated by commas. When working with dictionaries, […]
Create Unique List from List in Python
To get the unique items of a list in Python, the easiest way is by converting the list to a set with set() and then back to a list with list(). l = [0,7,7,7,0,2,3,1,1,4,5,6,7] l_unique = list(set(l)) print(l_unique) #Output: [0,1,2,3,4,5,6,7] If need to preserve the order of the elements in the list, then you can […]
Using Python to Remove Duplicates from List
To remove duplicates from a list in Python, the easiest way is by converting the list to a set with set() and then back to a list with list(). l = [0,7,7,7,0,2,3,1,1,4,5,6,7] l_duplicates_removed = list(set(l)) print(l_duplicated_removed) #Output: [0,1,2,3,4,5,6,7] If need to preserve the order of the elements in the list, then you can use comprehension. […]
Convert String to Float with float() in Python
To convert a string variable to a float in Python, use the float() function. x = "1" y = float(x) print(y) #Output: 1.0 When working with string variables in Python, the ability to easily be able to use and change these variables is valuable. One such situation is if you want to create a float […]
Convert String to Integer with int() in Python
To convert a string variable to an integer in Python, use the int() function. x = "1" y = int(x) print(y) #Output: 1 When working with string variables in Python, the ability to easily be able to use and change these variables is valuable. One such situation is if you want to create an integer […]
Using Python to Initialize Array of Size N
To initialize a list of size N in Python, the easiest way is to use * to multiply a single item list by N. n = 100 list_of_size_n = [0] * n list_of_size_n = [None] * n When working with numbers in a Python program, it’s possible you want to initialize an array of size […]
Create Empty List in Python
To create an empty list in Python, you can initialize a list with no items with open and closed square brackets. empty_list = [] In Python, lists are a collection of objects which are unordered. When working with lists, it can be useful to be able to easily create an empty list, or a list […]
Python Negative Infinity – How to Use Negative Infinity in Python
To use negative infinity in Python and create variables which represent negative infinity, there are four different ways. The easiest way to get negative infinity in Python is with the float() function. negative_infinity = -float('inf') print(negative_infinity) #Output: -inf Another way you can represent negative infinity in Python is with the math module. import math negative_infinity […]
Python Infinity – How to Use Infinity in Python
To use infinity in Python and create variables which represent infinity, there are four different ways. The easiest way to get infinity in Python is with the float() function. infinity = float('inf') print(infinity) #Output: inf Another way you can represent infinity in Python is with the math module. import math infinity = math.inf print(infinity) #Output: […]
Using Python to Check If List of Words in String
To check if a list of words is in a string using Python, the easiest way is with list comprehension. list_of_words = ["this","words","string"] string = "this is a string with words." print([word in string for word in list_of_words]) #Output: [True, True, True] If you want to check if all words of a list are in […]
Using Python to Print Environment Variables
To print environment variables using Python, use the os module and get the environment variables from the environ dictionary. import os print(os.environ) When working with operating systems, the ability to view, edit and work with environment variables easily can be valuable. If you want to see all of the environment variables of a user’s operating […]
Create List of Numbers from 1 to 100 Using Python
To create a list with the numbers from 1 to 100 using Python, we can use the range() function. list_1_to_100 = range(1, 101) You can also use a loop to create a list from 1 to 100 in Python. list_1_to_100 = [] for x in range(1,101): list_1_to_100.append(x) When working with numbers in a Python program, […]
How to Ask a Question in Python
To ask a question with Python, you can use the input() function. input() will prompt the user with the text and will return whatever text was input by the user. question = input("Do you want some ice cream?") When creating programs in Python, the ability to be able to ask questions and get a response […]
Check if Variable is Integer in Python
To check if a variable is an integer, you can use the type() function and check if the variable is of type int. t = 1 a = 1.01 l = [0, 1, 2] print(type(t) == int) print(type(a) == int) print(type(l) == int) #Output: True False False You can also use the isinstance() function to […]
Check if Variable is Float in Python
To check if a variable is a float, you can use the type() function and check if the variable is of type float. t = 1.01 a = 123 l = [0, 1, 2] print(type(t) == float) print(type(a) == float) print(type(l) == float) #Output: True False False You can also use the isinstance() function to […]
Write Float to File Using Python
To write a float to a file, you just have to open a file in write mode, convert the float to a string with str(), and use the write() function. fl = 1.01 with open("example.txt", "w") as f: f.write(str(fl)) If you want to add a float to an existing file and append to the file, […]
Write Integer to File Using Python
To write an integer to a file, you just have to open a file in write mode, convert the int to a string with str(), and use the write() function. integer = 1 with open("example.txt", "w") as f: f.write(str(integer)) If you want to add an integer to an existing file and append to the file, […]
Write Variable to File Using Python
To write a variable to a file, you just have to open a file in write mode and use the write() function. variable = "hello" with open("example.txt", "w") as f: f.write(variable) If you want to add a variable to an existing file and append to the file, then you need to open the file in […]
Run Something Every 5 Seconds in Python
To run code every 5 seconds in Python, you can use a loop and the Python time module sleep() function. import time for x in range(0,100): do_something() time.sleep(5) You can use a for loop or a while loop. import time while some_condition: do_something() time.sleep(5) When creating programs in Python, the ability to control when certain […]
Using Python to Append Character to String Variable
To append a character to a string in Python, the easiest way is with the + operator. string = "this is a string" character = "." string_appended = string + character print(string_appended) #Output: this is a string. When working with strings in Python, the ability to easily be able to modify the values of these […]
Check if Character is Letter in Python
To check if a character is a letter in Python, use the isalpha() function. To check if a string only contains letters in Python, you can use the string isalpha() function. a = "h" b = "b" c = "1" print(a.isalpha()) print(b.isalpha()) print(c.isalpha()) #Output: True True False When working with strings in Python, the ability […]
Check if Variable is Tuple in Python
To check if a variable is a tuple, you can use the type() function and check if the variable is of type tuple. t = (0, 1, 2) a = 1 l = [0, 1, 2] print(type(t) == tuple) print(type(a) == tuple) print(type(l) == tuple) #Output: True False False You can also use the isinstance() […]
Check if Variable is Datetime in Python
To check if a variable is a datetime, you can use the type() function and check if the variable is of type date or datetime. from datetime import datetime, date datetime_var = datetime.now() date_var = datetime_var.date() def checkDatetime(var): return type(var) == datetime def checkDate(var): return type(var) == date print(checkDatetime(datetime_var)) print(checkDate(datetime_var)) print(checkDatetime(date_var)) print(checkDate(date_var)) #Output: True False […]
String Contains Case Insensitive in Python
To check if a string contains a substring and ignore the case of the characters in the string, you can use the Python in operator and the lower() function. s = "this IS a StrING" def containsCaseInsensitive(substring, string): if substring.lower() in string.lower(): return True else: return False print(containsCaseInsensitive("is",s)) print(containsCaseInsensitive("THIS",s)) print(containsCaseInsensitive("z",s)) #Output: True True False You […]
Using Python to Check if String Contains Only Letters
To check if a string only contains letters in Python, you can use the string isalpha() function. a = "hello1" b = "bye" c = "123" print(a.isalpha()) print(b.isalpha()) print(c.isalpha()) #Output: False True False When working with strings in Python, the ability to check these strings for certain conditions is very valuable. One such case is […]
Check if String Contains Numbers in Python
To check if a string contains numbers in Python, you can create a function, loop over the string and check if any of the characters are numeric with isnumeric(). a = "hello1" b = "bye" c = "123" def containsNumbers(s): contains = False for char in s: if isnumeric(char): contains = True return contains print(containsNumbers(a)) […]
How to Sort Numbers in Python Without Sort Function
To sort a list of numbers in Python without a sort function, you can define your own function and loop through the list swapping numbers based on their values. def sort_without_sort(lst): for i in range(0, len(lst)): for j in range(i + 1, len(lst)): if lst[i] > lst[j]: lst[i], lst[j] = lst[j], lst[i] return lst print(sort_without_sort([9,2,5,4,1,0,7,5])) […]
Get pandas Series First Element in Python
To get the first element of a pandas series, the easiest way is to use iloc and access the ‘0’ indexed element. import pandas as pd s = pd.Series([0,1,2,3]) print(s.iloc[0]) #Output: 0 You can also use iat to get the first element of a pandas series. import pandas as pd s = pd.Series([0,1,2,3]) print(s.iat[0]) #Output: […]
Get pandas Series Last Element in Python
To get the last element of a pandas series, the easiest way is to use iloc and access the ‘-1’ indexed element. import pandas as pd s = pd.Series([0,1,2,3]) print(s.iloc[-1]) #Output: 3 You can also use iat to get the last element of a pandas series. import pandas as pd s = pd.Series([0,1,2,3]) print(s.iat[-1]) #Output: […]
Check if Class is Subclass in Python with issubclass()
To check if a class is a subclass in Python, the easiest way is with the issubclass() function. class Fruit: pass class Apple(Fruit): pass print(issubclass(Apple,Fruit)) print(issubclass(Fruit,Apple)) #Output: True False When working in Python, the ability to perform certain checks in our program is valuable. One such check is if you want to check if a […]
Draw Star in Python Using turtle Module
To draw a star in Python, we can use the Python turtle module. import turtle t = turtle.Turtle() def draw_star(size): for i in range(0,5): t.forward(size) t.right(144) draw_star(100) The turtle module in Python allows us to create graphics easily in our Python code. We can use the turtle module to make all sorts of shapes in […]
Decrement For Loop with range() in Python
To decrement a for loop in Python, the easiest way is to use range() and pass “-1” as the third argument to step by -1 after each iteration. for i in range(5,0,-1): print(i) #Output: 5 4 3 2 1 When working in Python, the ability to loop over objects and perform an action multiple times […]
Solve Python Object Does Not Support Indexing Error
When working in Python, receiving errors from our programs can be frustrating. One such error is when you get a TypeError because you try to access the index of an object that is not subscriptable or doesn’t support indexing. Such TypeErrors include: TypeError: ‘int’ object does not support indexing TypeError: list indices must be integers […]
Difference Between print and return in Python
When working with Python, there are many functions which seem similar but should be used for different cases. One such example is the use of the print() function and a return statement. Basically, the difference between print and return in Python is that print prints text to the terminal and return returns data from a […]
Difference Between read(), readline() and readlines() in Python
When reading files in Python, there are a few different functions you can use to extract text from a file. The three main functions you can use to read content from a file are read(), readline() and readlines(). read() reads the entire file and returns a string, readline() reads just one line from a file, […]
Using Python to Insert Tab in String
To use a tab in a string in Python, you can use the tab character “\t”. “\t” is the special character for tab. string="\thello" print(string) #Output: hello When working with strings, the ability to easily create, modify or remove characters from string is important. One such case is when you want to use special characters […]
Python os.sep – Create Operating System Path Seperator Character
In Python, when working with files and directories, paths are integral to being able to access what you want to access. To create separators which will work for any operating system, you can use the Python os module sep property. os.sep returns ‘/’ for POSIX and ‘\\’ for Windows. import os print(os.sep) #Output: '\\' When […]
Python turtle dot() – Draw Dot on Turtle Screen
To draw a circular dot with the Python turtle module, you can use the turtle dot() function. import turtle t = turtle.Turtle() t.dot() You can pass a size and a color to dot() if you want to make a dot with specific size or color. import turtle t = turtle.Turtle() t.dot(30,"green") The turtle module in […]
Python turtle write() – Write Text to Turtle Screen
To write text with the Python turtle module, you can use the turtle write() function. import turtle t = turtle.Turtle() t.write("Hello") You can write text with different font colors, font names, font sizes and font types. import turtle t = turtle.Turtle() t.color("blue") t.write("Hello", font=("Arial", 12, "normal") The turtle module in Python allows us to create […]
Python issuperset() Function – Check if Set is Superset of Another Set
The Python issuperset() function allows you to check if a set is a superset of another set. a = {1, 2, 3} b = {1, 2, 3, 4, 5, 6} print(b.issuperset(a)) #Output: True When working with different collections of data, the ability to easily determine properties of these objects can be useful. One such property […]
Python issubset() Function – Check if Set is Subset of Another Set
The Python issubset() function allows you to check if a set is a subset of another set. a = {1, 2, 3} b = {1, 2, 3, 4, 5, 6} print(a.issubset(b)) #Output: True When working with different collections of data, the ability to easily determine properties of these objects can be useful. One such property […]
Flatten List of Tuples in Python
To flatten a list of tuples in Python, the easiest way is to use list comprehension. list_of_tuples = [(0, 1), (2, 3), (4, 5)] flattened_list = [x for tuple in list_of_tuples for x in tuple] print(flattened_list) #Output: [0, 1, 2, 3, 4, 5] You can also use the sum() function. list_of_tuples = [(0, 1), (2, […]
Clear File Contents with Python
To clear the contents of a file in Python, the easiest way is to open the file in write mode and do nothing. with open("example.txt",'w') as f: pass Another way you can erase all contents in a file is with the truncate() function. with open("example.txt",'w') as f: f.truncate(0) If you want to clear only certain […]
Get Name of Function in Python
To get the name of a function when using Python, you can access the __name__ property. def function_example(): pass print(function_example.__name__) #Output: function_example If you are in a function and want to know the name of that function, then you can use the Python inspect module. import inspect def function_example(): frame = inspect.currentframe() return inspect.getframeinfo(frame).function print(function_example()) […]
Calculate Distance Between Two Points in Python
To calculate the distance between two points in Python, the easiest way is with the math module sqrt() function. import math p1 = (2, 4) p2 = (3, -5) distance = math.sqrt(((p2[0] – p1[0]) ** 2) + (p2[1] – p1[1]) ** 2) print(distance) #Output: 9.055385138137417 You can use the math module dist() function. The math […]
Convert List into Tuple Using Python
To convert a list into a tuple using Python, use the tuple() function. lst = ['h', 'e', 'l', 'l' ,'o'] t = tuple(lst) print(t) #Output: ('h', 'e', 'l', 'l', 'o') When working with different objects in Python, the ability to be able to convert objects into other objects can be valuable. One such situation is […]
Convert String into Tuple in Python
To convert a string into a tuple using Python, use the tuple() function. string = "hello" t = tuple(string) print(t) #Output: ('h', 'e', 'l', 'l', 'o') When working with different objects in Python, the ability to be able to convert objects into other objects can be valuable. One such situation is if you want to […]
Using Python to Increment Dictionary Value
To increment the value of a key in a dictionary using Python, simply add 1 to the value of the key. dictionary = {"counter":0} dictionary["counter"] = dictionary["counter"] + 1 print(dictionary) #Output: {'counter':1} In Python, dictionaries are a collection of key/value pairs separated by commas. When working with dictionaries, it can be useful to be able […]
Using Python to Split String by Tab
To split a string by tab in Python, you can use the Python string split() function and pass ‘\t’ to get a list of strings. string = "This is a\tstring with\ttab in it" print(string.split("\t")) #Output: ["This is a", "string with", "tab in it"] You can also use the split() function from the re (regular expression) […]
Python rjust Function – Right Justify String Variable
The Python rjust() function allows us to right justify string variables. string = "hello" print(string.rjust(8)) #Output: hello You can also pass a second parameter which will be used to fill the blank spaces created by rjust(). string = "hello" print(string.rjust(8, "x")) #Output: xxxhello When working with strings, the ability to easily modify the values of […]
Python ljust Function – Left Justify String Variable
The Python ljust() function allows us to left justify string variables. string = "hello" print(string.ljust(8)) #Output: hello You can also pass a second parameter which will be used to fill the blank spaces created by ljust(). string = "hello" print(string.ljust(8, "x")) #Output: helloxxx When working with strings, the ability to easily modify the values of […]
How to Add Commas to Numbers in Python
To add commas to numbers in Python, the easiest way is using the Python string formatting function format() with “{:, }”. amt = 3210765.12 amt2 = 1234.56 print("{:,}".format(amt)) print("{:,}".format(amt2)) #Output: 3,210,765.12 1,234.56 When working with numbers in Python, many times you need to format those numbers a certain way. One such situation is if you […]
How to Shutdown Computer with Python
To shutdown your computer with code in Python, you can use the os module system() function and pass “shutdown /s /t 1”. import os os.system("shutdown /s /t 1") If you want to shutdown the computer based on a condition, you can put this statement in an if statement. import os user_wants_shutdown = True if user_wants_shutdown: […]
Using Python to Count Number of Lines in String
To count the number of lines in a string, the easiest way is to use split() and split the line with the newline character. Then use len() string = "This is a\nstring with\nnewline in it" count = len(string.split("\n")) print(string.split("\n")) print(count) #Output: ["This is a", "string with", "newline in it"] 3 You can also use the […]
Check if String Does Not Contain Substring in Python
In Python, we can easily check if a string does not contains a substring using the in operator and not operator. string = "Hello" if "z" not in string: print("z not in string") else: print("z in string") #Output: z not in string When working with strings, it can be useful to know if a substring […]
Sort by Two Keys in Python
To sort a list of objects by two keys in Python, the easiest way is with the key parameter and a tuple of the keys you want to sort by. list_of_dicts = [{"name":"Bob","weight":100,"height":50}, {"name":"Sally","weight":120,"height":70}, {"name":"Jim","weight":120,"height":60}, {"name":"Larry","weight":150,"height":60}] list_of_dicts.sort(key= lambda x: (x["weight"],x["name"])) print(list_of_dicts) #Output: [{'name': 'Bob', 'weight': 100, 'height': 50}, {'name': 'Jim', 'weight': 120, 'height': 60}, {'name': […]
Unset Environment Variables in Python
To unset environment variables in Python, the easiest way is to remove the variable from the os module environ dictionary with pop(). import os os.environ.pop("VARIABLE_TO_UNSET", None) You can also use del if you know the variable is in the environ dictionary. If the variable is not in the dictionary, you will get a KeyError. import […]
Read Last N Lines of File in Python
To read the last N Lines of a file in Python, the easiest way is to use the Python file readlines() function and then access the last N elements of the returned list. n = 5 with open("example.txt") as f: last_n_lines = f.readlines()[-n:] When working with files, the ability to easily read from or write […]
Read Last Line of File Using Python
To read the last line of a file in Python, the easiest way is with the Python file readlines() function. with open("example.txt") as f: last_line = f.readlines()[-1] One other way you can read the last line of a file is with the read() function and then split it on the new line character. with open("example.txt") […]
Read First Line of File Using Python
To read the first line of a file in Python, the easiest way is with the Python file readline() function. with open("example.txt") as f: first_line = f.readline() You can also use the Python readlines() function and access the first item to get the first line of a file. with open("example.txt") as f: first_line = f.readlines()[0] […]
Negate Boolean in Python with not Operator
To negate a boolean variable in Python, the easiest way is with the not operator. bool_var = True print(not bool_var) #Output: False When working with conditional expressions, the ability to change their values easily is valuable. One such case is if you want to negate a conditional and negate a boolean value. In some programming […]
Check if Number is Larger than N in Python
To check if a number if larger than a given number N in Python, the easiest way is with the greater than > operator and an if statement. num = 12 N = 10 if num > N: print("num is larger than N") else: print("num is smaller than N") #Output: num is larger than N […]
Are Tuples Mutable in Python? No, Tuples are not Mutable
In Python, there are mutable and inmutable data types. Mutable data types can be changed after it has been created. Inmutable data types cannot be changed after they have been created. Are tuples mutable in Python? No, tuples are not mutable in Python and are inmutable. With tuples, we cannot add or remove elements of […]
Are Dictionaries Mutable in Python? Yes, Dictionaries are Mutable
In Python, there are mutable and inmutable data types. Mutable data types can be changed after it has been created. Inmutable data types cannot be changed after they have been created. Are dictionaries mutable in Python? Yes, dictionaries are mutable in Python. With dictionaries, we can add and remove items easily, and also change existing […]
How Clear a Set and Remove All Items in Python
In Python, to remove all elements from a set, the easiest way is with the clear() function. After using clear(), you’ll have an empty set. set_with_elements = {"whale","dog","cat"} set_with_elements.clear() print(set_with_elements) #Output: set() In Python, sets are a collection of elements which are unordered and mutable. When working with sets, it can be useful to be […]
Using Python to Count Number of False in List
To count the number of False values in a list in Python, the easiest way is with list comprehension and the Python len() function. lst = [True, False, True, False] count = len([val for val in lst if val == False]) print(count) #Output: 2 If you have a list which has numbers in it, you […]
Using Python to Count Number of True in List
To count the number of True values in a list in Python, the easiest way is with list comprehension and the Python len() function. lst = [True, False, True, False] count = len([val for val in lst if val == True]) print(count) #Output: 2 If you have a list which has numbers in it, you […]
Convert False to 0 in Python
To convert the boolean value False to 0 in Python, you can use int(). int() converts False to 0 explicitly. print(int(False)) #Output: 0 You can also convert False to 0 implicitly in the following way. print(False == 0) #Output: True When working with different variable types in Python, the ability to easily convert between those […]
Convert True to 1 in Python
To convert the boolean value True to 1 in Python, you can use int(). int() converts True to 1 explicitly. print(int(True)) #Output: 1 You can also convert True to 1 implicitly in the following way. print(True == 1) #Output: True When working with different variable types in Python, the ability to easily convert between those […]
Append Multiple Elements to List Using Python
To append multiple elements to a list in Python, the easiest way is with the + operator. a = [1, 2, 3] b = [4, 5, 6] c = a + b print(c) #Output: [1, 2, 3, 4, 5, 6] You can also use the Python extend() function. extend() appends another list in place and […]
pandas startswith() – Check if String Starts With Certain Characters
To check if a string starts with certain characters when using pandas, you can use the pandas startswith() function. df["Name"].str.startswith("M") #Return boolean series with values showing which rows have a name starting with M When working with data, the ability to get, search for or filter information from your data. With the pandas package, there […]
Check if Line is Empty in Python
To check if a line is empty when reading from a file in Python, the easiest way is by checking if the line is equal to newline characters. myfile = open("example.txt", "r") lines = myfile.readlines() for line in lines: if line in ['\n','\r\n']: #line is empty… You can check if a line is not empty […]
Using Python to Sum Odd Numbers in List
To sum the odd numbers in a list in Python, the easiest way is with list comprehension and the Python sum() function. lst = [0, 4, 6, 9, 2, 3, 1] s = sum([num for num in lst if num % 2 != 0]) print(s) #Output: 13 You can also use a loop to sum […]
Using Python to Sum Even Numbers in List
To sum the even numbers in a list in Python, the easiest way is with list comprehension and the Python sum() function. lst = [0, 4, 6, 9, 2, 3, 1] s = sum([num for num in lst if num % 2 == 0]) print(s) #Output: 12 You can also use a loop to sum […]
Using Python to Count Odd Numbers in List
To count the odd numbers in a list in Python, the easiest way is with list comprehension and the Python len() function. lst = [0, 4, 6, 9, 2, 3, 1] count = len([num for num in lst if num % 2 != 0]) print(count) #Output: 3 You can also use a loop to count […]
Using Python to Count Even Numbers in List
To count the even numbers in a list in Python, the easiest way is with list comprehension and the Python len() function. lst = [0, 4, 6, 9, 2, 3, 1] count = len([num for num in lst if num % 2 == 0]) print(count) #Output: 4 You can also use a loop to count […]
Using Selenium to Close Browser in Python
To close the browser when using Selenium in Python, the easiest way is to use the Selenium webdriver close() function. from selenium import webdriver driver = webdriver.Chrome() driver.get("http://theprogrammingexpert.com/") driver.close() If you want to end the driver session, which also closes the browser, you can use the Selenium webdriver quit() function. from selenium import webdriver driver […]
Generate Random Float Between 0 and 1 Using Python
To generate a random float in between 0 and 1, the easiest way is with the random function from the Python random module. import random for x in range(0,3): print(random.random()) #Output: 0.5766391709474086 0.6620907660748007 0.8046101146489392 You can also use the uniform() function from the Python random module. import random for x in range(0,3): print(random.uniform(0,1)) #Output: 0.142756405376938 […]
Find Maximum of Three Numbers in Python
To find the maximum of three numbers in Python, the easiest way is to use the Python max() function. a = 5 b = 10 c = 15 print(max(a,b,c)) #Output 15 If you have the three numbers in a list, you can pass the list to max() and get the maximum value. If you have […]
How to Split List in Half Using Python
To split a list in half using Python, the easiest way is with list slicing. list_of_numbers = [0, 1, 2, 3, 4, 5] first_half = list_of_numbers[:3] second_half = list_of_numbers[3:] print(first_half) print(second_half) #Output: [0, 1, 2] [3, 4, 5] You can easily create a function which will find the middle position of a given list and […]
Remove None From List Using Python
To remove all instances of None from a list using Python, the easiest way is to use list comprehension. lst = [1,2,3,4,None,2,1,None,3,2] list_without_none = [x for x in lst if x != None] print(list_without_none) #Output: [1, 2, 3, 4, 2, 1, 3, 2] You can also use the Python filter() function. lst = [1,2,3,4,None,2,1,None,3,2] list_without_none […]
Using Python to Capitalize Every Other Letter of String
To capitalize every other letter of a string in Python, the easiest way is with a loop inside a function. def capitalize_every_other(string): result = "" prev_char_cap = False #we want first letter to be capitalized for char in string: if prev_char_cap: result = result + char.lower() else: result = result + char.upper() prev_char_cap = not […]
How to Rotate String in Python
In Python, the easiest way to rotate characters in a string is with slicing. You can rotate a string backwards or forwards with slicing. string = "hello" string_rotated_backwards = string[1:] + string[:1] string_rotated_forward = string[-1:] + string[:-1] print(string_rotated_backwards) print(string_rotated_forward) #Output: elloh ohell In Python, strings are one of the most used data structures. When working […]
Calculate Sum of Dictionary Values in Python
To sum the values of a dictionary in Python, the easiest way is with the Python sum() function used on the dictionary values. d = {'a': 4, 'b': 5, 'c': 6} print(sum(d.values()) #Output: 15 You can also use comprehension to sum the values of a dictionary in Python. d = {'a': 4, 'b': 5, 'c': […]
Concatenate Multiple Files Together in Python
You can concatenate files in Python easily. To concatenate two files, you can read the content from both files, store the contents in strings, concatenate the strings and then write the final string to a new file. with open('file1.txt') as f: f1 = f.read() with open('file2.txt') as f: f2 = f.read() f3 = f1 + […]
Using Python to Reverse Tuple
To reverse a tuple in Python, the easiest way is slicing. t = (0, 1, 2, 3) t_reversed = t[::-1] print(t_reversed) #Output: (3, 2, 1, 0) You can also use reversed() to create a reversed object and build a new tuple from scratch. t = (0, 1, 2, 3) new_tuple = () for x in […]
Using Python to Sort Two Lists Together
To sort two lists together in Python, and preserve the order of pairs, you can use comprehension, zip() and sorted(). It is a little complicated, as we will explain here shortly, but here is some sample code for how you can sort two lists together using Python. list1 = [1,4,4,2,3,3] list2 = [8,7,6,9,9,3] list1, list2 […]
How to Check if Number is Negative in Python
To check if a number is negative using Python, you can use the less than operator
How to Check if Variable is Defined in Python
Checking if a variable is defined in Python is easy. To check if a variable is defined, the easiest way is with exception handling. try: print(variable) except NameError: print("variable isn't defined") #Output: variable isn't defined. You can use the Python globals() functions to check if a variable is defined globally. variable = "this is a […]
Using readlines() and strip() to Remove Spaces and \n from File in Python
When reading the contents of a file, whitespace sometimes can cause us troubles. To remove whitespace from each line when using Python, you can use the Python strip() function. myfile = open("example.txt", "r") lines = myfile.readlines() for line in lines: stripped_line = line.strip() When working with files, if you have bad inputs, you can have […]
Get Length of File Using Python
To get the length of a file, or the number of lines in a file, you can use the Python readlines() and len() functions. with open("example.txt","r") as f: print(len(f.readlines())) #Output: 101 When working with files, the ability to get different statistics about the file easily can be useful. One such statistic is the length of […]
Using Python to Remove Non-Empty Directory
To remove a non-empty directory in Python, the easiest way is to use the shutil module rmtree() function. import shutil shutil.rmtree(path) When working with files and folders in Python, the ability to easily create or delete files and folders can be useful. One such situation is if you want to remove a non-empty directory. The […]
Calculating Sum of Squares in Python
To find the sum of the squares of a list of numbers in Python, the easiest way is with a for loop. def sum_of_squares(lst): sum = 0 for x in lst: sum = sum + x ** 2 return sum print(sum_of_squares(range(10))) # range(0,1,2,3,4,5,6,7,8,9) print(sum_of_squares([4,6,2,9,10])) #Output: 285 237 You can also use sum() and list comprehension […]
Using Python to Check If a Number is a Perfect Square
In Python, you can easily check if a number is a perfect square by taking the square root and checking if the square root is an integer. a = 49 b = 20 c = 16 def check_perfect_square(num): return int(num ** (1/2)) == num ** (1/2) print(check_perfect_square(a)) print(check_perfect_square(b)) print(check_perfect_square(c)) #Output: True False True When working […]
Get Week Number from Date in Python
To get the week number from a date or datetime object in Python, the easiest way is to use the Python isocalendar() function. import datetime print(datetime.date(2022, 6, 20).isocalendar()[1]) #Output: 25 The Python datetime strftime() function also can be helpful to get the week number from the date in Python, depending on which calendar you want […]
How to Check If File is Empty with Python
To check if a file is empty in Python, the easiest way is check if a file has size 0 with the os.path module getsize() function. import os if os.path.getsize("C:/Users/TheProgrammingExpert/example.txt") == 0: print("file is empty") else: print("file is not empty") #Output: file is empty You can also use the os module stat() function to get […]
Python Turtle Fonts – How to Write Text with Different Fonts in Python
To write text with the Python turtle module, you can use the Python turtle write() function and pass the font parameter a font name, font size and font type. import turtle t = turtle.Turtle() t.write("Hello", font=("Arial", 12, "normal") The turtle module in Python allows us to create graphics easily in our Python code. We can […]
Write Inline If and Inline If Else Statements in Python
To create an inline if statement in Python, you can use the Python ternary operator. a = 1 b = 2 if a == 1 print(b) #Output: 2 You can also write inline if else statements with the ternary operator in Python. a = 1 b = 2 if a > 2 else 3 print(b) […]
Initialize Multiple Variables in Python
To initialize multiple variables in a single line of code in Python, you can use tuple unpacking to initialize multiple variables. a, b = 1, 2 print(a) print(b) #Output: 1 2 You can also use semicolons to create multiple variables. a = 1; b = 2; print(a) print(b) #Output: 1 2 When programming, variables are […]
Does Python Use Semicolons? Why Python Doesn’t Use Semicolons
In general, Python does not use semicolons as Python is a “whitespace delimited” language. While other programming languages require the use of semicolons to end code statements, you do not need to put a semicolon at the end of your lines of code in Python. string_variable = "no semicolon at the end of this statement" […]
Truncate String in Python with String Slicing
To truncate a string variable in Python, you can use string slicing and create a slice depending on your use case. Below is a simple example of how to truncate a string with slicing in Python string_variable = "This is a string of words" truncated_string_to_10_chars = string_variable[:10] print(truncated_string_to_10_chars) #Output: This is a When working with […]
Truncate Decimal from Number with Python math.trunc() Function
The Python math module trunc() function returns the truncated integer part of a floating point number. You can use trunc() to truncate the decimal of a floating point number in Python. import math num = 1.53 print(math.trunc(num)) #Output: 1 When working with numbers, the ability to easily format and change the value of different numbers […]
Remove Decimal from Float in Python
There are three ways you can remove the decimal from a floating point number in Python. Depending on what you want to accomplish, any of these ways might work for you. The first way is to use the Python round() function. num = 1.53 print(round(num)) #Output: 2 You can also use the Python math module […]
How to Return Nothing in Python from Function
You can return nothing in Python from a function in three ways. The first way is by omitting a return statement. def someFunction(x): x = x * 2 print(someFunction(2)) #Output: None The second way is by including a blank return statement. def someFunction(x): x = x * 2 return print(someFunction(2)) #Output: None The third way […]
Change Python Turtle Shape Fill Color with fillcolor() Function
When using the turtle module in Python, you can Use the fillcolor() function to define the fill color of a shape, and then use the begin_fill() and end_fill() functions to define when to begin and end filling shapes with the fill color. import turtle t = turtle.Turtle() t.fillcolor("blue") t.begin_fill() t.circle(50) t.end_fill() The turtle module in […]
Rename Key in Dictionary in Python
When working with dictionaries in Python, to rename a key, you can use the dictionary pop() function. dictionary = {"apples":3, "bananas":4, "pears":5} dictionary["watermelon"] = dictionary.pop("apples") print(dictionary) #Output: {"bananas":4, "pears":5, "watermelon":3} You can also use the del keyword to rename a key in a dictionary variable in Python. dictionary = {"apples":3, "bananas":4, "pears":5} dictionary["watermelon"] = dictionary["apples"] […]
Why Dictionaries Can’t Have Duplicate Keys in Python
In Python, dictionary variables cannot have duplicate keys as by definition, they cannot have duplicate keys. If you try to define a dictionary with duplicate keys, the last key will be kept with all other duplicate keys removed. d = {"name":"Bobby", "name":"Sam", "name":"Alex", "height":65, "height":100, "income":65} print(d) #Output: {'name': 'Alex', 'height': 100, 'income': 65} In […]
Inverting Dictionary Variables in Python with Dictionary Comprehension
To invert a dictionary and swap the keys and values of a dictionary in Python, use dictionary comprehension and swap the keys and values. d = {"name":"Bobby", "age":20,"height":65} d_inverted = {value: key for key, value in d.items()} print(d_inverted) #Output: {'Bobby': 'name', 20: 'age', 65: 'height'} When working with dictionaries in Python, the ability to modify […]
Python getsizeof() Function – Get Size of Object
The Python getsizeof() function allows you to get the size (in bytes) of objects in your Python programs. import sys print(sys.getsizeof(3)) print(sys.getsizeof("hello")) print(sys.getsizeof([0, 1, 2, 3])) #Output: 28 54 120 When working with objects in Python, the ability to easily be able to get different pieces of information about the objects can be valuable. One […]
Python divmod() Function – Get Quotient and Remainder After Division
The Python divmod() function allows us a way to easily get the quotient and remainder after division of two numbers. print(divmod(15,4)) #Output: (3, 3) When performing different calculations with numbers in Python, the ability to easily get certain pieces of information about the calculation can be useful. One such case is when dividing by two […]
Find Quotient and Remainder After Division in Python
To get the quotient and remainder after division of two numbers in Python, the easiest way is with the Python divmod() function. print(divmod(10,3)) #Output: (3, 1) You can also create your own function and use integer division and the % operator to get the quotient and remainder afster division. def quo_rem(a,b): return a // b, […]
Calculate Compound Interest in Python
To calculate compound interest in Python, you can use the formula to calculate compound interest and create a function. def compound_interest(p,r,n,t): a = p*(1+r/100/n)**(n*t) return a – p print(compound_interest(1000,5,1,10)) #Output: 628.894626777442 If you have continuous compounding and want to calculate the compound interest, then you can use the continuous compounding equation. import math def compound_interest(p,r,t): […]
Using Python to Print Plus or Minus Sign Symbol
In Python, to print the plus or minus symbol, you can use the unicode for the plus or minus sign ‘\u00B1’. print('\u00B1') ± When outputting text to the console or to a file, the ability to write different symbols easily is valuable. One such symbol which is commonly used is the plus or minus symbol. […]
Using Python to Print Degree Symbol
In Python, to print the degree symbol, you can use the unicode for the degree sign ‘\u00B0’. print('\u00B0') ° When outputting text to the console or to a file, the ability to write different symbols easily is valuable. One such symbol which is commonly used is the degree symbol. Degrees are used in different areas […]
Print Approximately Equal Symbol in Python
In Python, to print the approximately equal symbol, you can use the unicode for approximately equal ‘\u2245’. print('\u2245') #Output: ≅ Other unicodes which might be useful depending on what you are trying to accomplish are shown below which are similar to approximately equal. print('\u2246') print('\u2247') print('\u2248') print('\u2249') #Output: ≆ ≇ ≈ ≉ When outputting text […]
Using Python to Add Trailing Zeros to String
To add trailing zeros to a string in Python, the easiest way is with the + operator. string = "hello" print(string + "000") #Output: hello000 You can also use the Python string ljust() function to add trailing zeros to a string. string = "hello" print(string.ljust(8,"0")) #Output: hello000 One last way is with the format() function. […]
Using Python to Convert Integer to String with Leading Zeros
To convert an integer to a string with leading zeros in Python, the easiest way is with the str() function and + operator. integer = 123 print("000" + str(integer)) #Output: 000123 You can also use the Python string rjust() function to add leading zeros to a number after converting it to a string. integer = […]
Remove Leading and Trailing Characters from String with strip() in Python
The Python strip() function is very useful when working with strings. strip() removes a given character from the beginning and end of a string. str = " 1234 " print(str.strip()) #Output: 1234 When working with strings, the ability to easily be able to manipulate and change the values of those strings is valuable. One such […]
Remove Trailing Zeros from String with rstrip() in Python
To remove trailing zeros from a string in Python, the easiest way is to use the Python string rstrip() function. str = "12340000" print(str.rstrip("0")) #Output: 1234 You can also use a while loop and slicing to remove trailing zeros from a string. str = "12340000" while str[0] == "0": str[:-1] print(str) #Output: 1234 When working […]
Remove Leading Zeros from String with lstrip() in Python
To remove leading zeros from a string in Python, the easiest way is to use the Python string lstrip() function. str = "00001234" print(str.lstrip("0")) #Output: 1234 You can also use a while loop and slicing to remove leading zeros from a string. str = "00001234" while str[0] == "0": str[1:] print(str) #Output: 1234 When working […]
Format Numbers as Currency with Python
To format numbers as currency in Python, the easiest way is with the locale module. import locale locale.setlocale( locale.LC_ALL, '' ) amt = 1234.56 print(locale.currency(amt)) print(locale.currency(amt, grouping=True)) #Output: $1234.56 $1,234.56 You can also use the string format() function. amt = 1234.56 print("${:.2f}".format(amt)) print("${:0,.2f}".format(amt)) #Output: $1234.56 $1,234.56 Finally, you can use the babel.numbers module to format […]
Format Numbers as Dollars in Python with format()
To format a number with a dollar format in Python, the easiest way is using the Python string formatting function format() with “${:.2f}”. amt = 12.34 amt2 = 1234.56 print("${:.2f}".format(amt)) print("${:.2f}".format(amt2)) #Output: $12.34 $1234.56 If you want to include commas for numbers over 1,000, then you can use “${:0,.2f}” following to format numbers as dollars. […]
Perform Reverse Dictionary Lookup in Python
There are a few ways you can do a reverse dictionary lookup in Python. The easiest way to perform a reverse dictionary lookup in Python is with a for loop. d = {"name":"Bobby", "age":20,"height":65} for key, value in d.items(): if value == "Bobby": print(key) #Output: name You can also invert the dictionary with dictionary comprehension […]
Random Number Without Repeating in Python
To generate random numbers without repeating in Python, you can use the random module function choices(). choices() takes a list and the number of random numbers you want to generate. import random lst = range(0,100) print(random.choices(lst, k=10)) #Output: [37, 95, 88, 82, 15, 38, 60, 71, 56, 49] When working with data, it can be […]
Using Lambda Expression with min() in Python
The Python min() function allows you use a lambda expression to apply a function to the elements of a list before finding the minimum value. You can easily define a lambda expression and use it with min(). example_list = [0, 3, 1, -3, -5, 4] print(min(example_list, key=lambda x:abs(x))) #Output: 0 When working with collections of […]
Using Lambda Expression with max() in Python
The Python max() function allows you use a lambda expression to apply a function to the elements of a list before finding the maximum value. You can easily define a lambda expression and use it with max(). example_list = [0, 3, 1, -3, -5, 4] print(max(example_list, key=lambda x:abs(x))) #Output: -5 When working with collections of […]
Check if String is Date in Python
To check if a string is a date, you can use the Python strptime() function from the datetime module. strptime() takes a string and a date format. from datetime import datetime string = "06/02/2022" format_ddmmyyyy = "%d/%m/%Y" format_yyyymmdd = "%Y-%m-%d" try: date = datetime.strptime(string, format_ddmmyyyy) print("The string is a date with format " + format_ddmmyyyy) […]
Using Python to Compare Strings Alphabetically
To compare strings alphabetically in Python, you can use the < (less than), > (greater than), = (greater than or equal to) operators. a = "this is a string" b = "another string" if a < b: print("a is less than b") else: print("a is greater than or equal to b") #Output: a is greater […]
Using Python Selenium Webdriver to Refresh Page
To refresh a web page when using Selenium in Python, the easiest way is to use the Selenium webdriver refresh() function. from selenium import webdriver driver = webdriver.Chrome() driver.get("http://theprogrammingexpert.com/") driver.refresh() The Selenium Python module gives you the tools you need to be able to automate many tasks when working with web browsers. When working with […]
Using Selenium to Check if Element Exists in Python
To check if an element exists in a web page when using the Python Selenium module, the easiest way is with the Selenium webdriver find_element() or find_elements() functions. find_element() returns a single element if it is found, and find_elements() returns a list if the elements are found. If elements are not found, a NoSuchElementException is […]
Get Substring Between Two Characters with Python
To get the substring between two characters in a string with Python, there are a few ways you can do it. The easiest way is with the index() function and string slicing. string = "Word1aWord2bWord3" between_a_and_b = string[string.index("a") + 1: string.index("b")] print(between_a_and_b) #Output: Word2 You can also use the regular expression re module to get […]
Using Python to Split String into Dictionary
To split a string into a dictionary using Python, the easiest way is to use the Python split() function and dictionary comprehension. With this method, you will get a dictionary where the keys are numbers and the values are the words of the string. string = "this is a string with some words" d = […]
Using Python to Split String by Newline
To split a string by newline in Python, you can use the Python string split() function and pass ‘\n’ to get a list of strings. string = "This is a\nstring with\nnewline in it" print(string.split("\n")) #Output: ["This is a", "string with", "newline in it"] You can also use the split() function from the re (regular expression) […]
Using Selenium to Get Text from Element in Python
To get the text from an HTML element when using Selenium in Python, you can use the attribute() function and accessing the ‘textContent’, ‘text’, or ‘innerText’ attributes. from selenium import webdriver driver = webdriver.Chrome() driver.get("http://theprogrammingexpert.com/") header = driver.find_element_by_css_selector("h1") print(header.attribute('textContent')) #Output: The Programming Expert The Selenium Python module gives you the tools you need to be […]
Check if Number is Between Two Numbers Using Python
In Python, you can easily check if a number is between two numbers with an if statement, and the and logical operator. def between_two_numbers(num,a,b): if a < num and num < b: return True else: return False You can also use the Python range() function to check if a number is in a range between […]
Scroll Up Using Selenium in Python
To scroll up using Selenium in Python, you can use the Selenium webdriver execute_script() function which executes JavaScript code in the browser. from selenium import webdriver driver = webdriver.Chrome() driver.get("http://theprogrammingexpert.com/") #Scroll to Top of Webpage driver.execute_script("window.scrollTo(0,0)") The Selenium Python module gives you the tools you need to be able to automate many tasks when working […]
Scroll Down Using Selenium in Python
To scroll down using Selenium in Python, you can use the Selenium webdriver execute_script() function which executes JavaScript code in the browser. from selenium import webdriver driver = webdriver.Chrome() driver.get("http://theprogrammingexpert.com/") #Scroll to Bottom of Webpage driver.execute_script("window.scrollTo(0,document.body.scrollHeight)") The Selenium Python module gives you the tools you need to be able to automate many tasks when working […]
Selenium maximize_window() Function to Maximize Window in Python
To maximize the browser window using Selenium in Python, you can use the Selenium webdriver maximize_window() function. from selenium import webdriver driver = webdriver.Chrome() driver.get("http://theprogrammingexpert.com/") driver.maximize_window() The Selenium Python module gives you the tools you need to be able to automate many tasks when working with web browsers. When working with a browser, there might […]
Selenium minimize_window() Function to Minimize Window in Python
To minimize the browser window using Selenium in Python, you can use the Selenium webdriver minimize_window() function. from selenium import webdriver driver = webdriver.Chrome() driver.get("http://theprogrammingexpert.com/") driver.minimize_window() The Selenium Python module gives you the tools you need to be able to automate many tasks when working with web browsers. When working with a browser, there might […]
Get Current URL with Selenium in Python
To get the current URL of a web page when using Selenium in Python, you can use the Selenium webdriver current_url attribute. from selenium import webdriver driver = webdriver.Chrome() driver.get("http://theprogrammingexpert.com/") print(driver.current_url) #Output: http://theprogrammingexpert.com/ The Selenium Python module gives you the tools you need to be able to automate many tasks when working with web browsers. […]
Python isfinite() Function – Check if Number is Finite with math.isfinite()
To check if a number is finite or not in Python, you can use the math module isfinite() function. isfinite() returns a boolean value which tells us if the input number is finite or not. import math print(math.isfinite(10)) print(math.isfinite(float('inf'))) #Output: True False The Python math module has many powerful functions which make performing certain calculations […]
Deque Peek and Queue Peek Functions in Python
When using queues in different programming languages, usually there exists a “peek” function which allows us to view the element at the beginning of a queue. In Python, we can implement a queue data structure using the collections module or the queue module. Unfortunately, neither of these modules have a “peek” function. If you want […]
Open Multiple Files Using with open in Python
To open multiple files in Python, you can use the standard with open() as name syntax and for each additional file you want to open, add a comma in between the with open statements. with open("file1.txt","w") as f1, open("file2.txt","w") as f2: #do stuff here When working with files in Python, the ability to open multiple […]
Get Random Value from Dictionary in Python
To get a random value from a dictionary in Python, you can use the random module choice() function, list() function and dictionary values() function. import random d = {"a":3, "b": 5, "c":1, "d":2} print(random.choice(list(d.values()))) #Output: 5 If you want to get a random key from a dictionary, you can use the dictionary keys() function instead. […]
Using Python to Get Queue Size
Getting the size of a queue in Python is easy. There are a few ways you can implement a queue in Python. If you are using deque from the collections module, you can use the len() function to get the size of your queue. from collections import deque q = deque() q.append(1) q.append(2) q.append(3) print(len(q)) […]
Create Empty Tuple in Python
Empty tuples in Python can be useful for you if you want to initialize a tuple or check if a tuple is empty. To create an empty tuple, you can use parenthesis with nothing in between or use the Python tuple() function. empty_tuple_1 = () empty_tuple_2 = tuple() In Python, tuples are a collection of […]
Using Python to Get Home Directory
There are a few different ways you can get the home directory using Python. The simplest way to get the user home directory on all platforms in Python is with the os.path.expanduser() function. import os print(os.path.expanduser('~')) #Output: 'C\\Users\\TheProgrammingExpert' You can also use Path.home() from the pathlib module. from pathlib import Path print(Path.home()) #Output: C\Users\TheProgrammingExpert When […]
Count Values by Key in Python Dictionary
To count the values by key in a Python dictionary, you can use comprehension to loop over the dictionary items, and then count the number of items for a given key with the Python len() function. d = { "a":[1,2,3], "b":[1,2,3,4,5], "c":[1,2], "d":[1,2,3,4,5,6,7] } count = { k: len(v) for k, v in d.items() } […]
Skip Numbers in Python Range
In Python, you can use the optional ‘step’ parameter to skip numbers in a range. If you are using a range object in a loop, the ‘step’ parameter will allow you to skip iterations. print("skipping all odds in range with 'step' parameter") print(list(range(0,20,2))) #Output: skipping all odds in range with 'step' parameter [0, 2, 4, […]
Using Python to Create List of Prime Numbers
In Python, we can create a list of prime numbers easily – all we need is a custom function to check if a number is prime or not. To generate a list of the first N prime numbers in Python, you can create your own function and loop until you have N prime numbers. def […]
Using Python to Check if Deque is Empty
To check if a deque variable is empty in Python, you can check if the deque has length 0. from collections import deque d = deque() print(len(d) == 0) #Output: True You can also convert it to a boolean and check if the deque converted to a boolean is False. from collections import deque d […]
Create Empty String Variable in Python
To create an empty string in Python, you can use single or double quotes. empty_string_with_single_quotes = '' empty_string_with_double_quotes = "" When working with string variables and text in Python, the ability to create variables with specific values can be useful. One such string which is unique is the empty string. You can create an empty […]
Using Python to Read Random Line from File
To read a random line from a file in Python, you can use the Python random module with the read() and splitlines() functions. import random with open("example.txt","r") as file: lines = file.read().splitlines() print(random.choice(lines)) When working with files, the ability to easily extract different pieces of information can be very valuable. One such piece of information […]
Using Python to Search File for String
To search a file for a string using Python, you can use the read() function and use the Python in operator to check each line for a particular string. string = "word" in_file = False with open("example.txt","r") as f: if string in f.read(): in_file = True print(in_file) #Output: True When working with files in Python, […]
How to Iterate Through Lines in File with Python
To iterate through lines in a file using Python, you can loop over each line in a file with a simple for loop. with open("example.txt","r") as f: for line in f: #do something here When reading files, the ability to read files sequentially line by line can be very useful. Reading text from a file […]
Using Python to Read File Character by Character
To read a file character by character using Python, you can loop over each line in a file and then loop over each character in each line. with open("example.txt","r") as f: for line in f: for char in line: #do something here When reading files, the ability to read files sequentially character by character can […]
Using Python to Read File Word by Word
To read a file word by word using Python, you can loop over each line and then loop over all of the words in the line. with open("example.txt","r") as f: for line in f: for word in line.split(" "): #do something here When reading files, the ability to read files sequentially word by word can […]
Sort Files by Date in Python
To sort files by date using Python, you can use the os module listdir() function to get all files in a directory. Then use the os.path.getcttime() or os.path.getmttime() to get the file creation or modification dates, respectively, inside a sort function. import os files = os.listdir() print(files) files.sort(key=lambda x: os.path.getmtime(x)) #Sort by Modification Time print(files) […]
Using Python to Find Closest Value in List
To find the closest value to a given number in a list of numbers, the easiest way is to use the Python min() function with a lambda function. lst = [5, 6, 10, 15, 21, 14, -1] n = 13 closest = min(lst, key=lambda x: abs(x-n)) print(closest) #Output: 14 You can also use the numpy […]
Remove Extension from Filename in Python
To remove the extension from a filename using Python, the easiest way is with the os module path.basename() and path.splitext() functions. import os filename = os.path.basename("C:/Users/TheProgrammingExpert/example.png") filename_without_ext = os.path.splitext(filename)[0] print(filename) print(filename_without_ext) #Output: example.png example You can also use the pathlib module and Path and then access the attribute ‘stem’ to remove the extension from a […]
Get Size of File in Python with os.path.getsize() Function
To get the size of a file in Python, the easiest way is with the os.path module getsize() function. import os print(os.path.getsize("C:/Users/TheProgrammingExpert/example.png")) #Output: 351 You can also use the os module stat() function to get the size of a file in Python. import os print(os.stat("C:/Users/TheProgrammingExpert/example.png").st_size) #Output: 351 Finally, if you are using the pathlib module […]
Using Python to Count Items in List Matching Criteria
In Python, to count the items in a list which match a certain criterion, you can use comprehension and the Python sum() function. lst = [5, 6, 2, 9, -1, 3] count_gt_4 = sum(x > 4 for x in lst) print(count_gt_4) #Output: 3 You can also use an if statement to count items in a […]
Using Python to Generate Random String of Specific Length
To generate a random string of specified length in Python, you can use the random module, comprehension and the Python join() function. import string from random import randint def random_char(): alphabet = list(string.ascii_lowercase) return alphabet[randint(0,25)] def random_string(n): return ''.join(random_char() for _ in range(n)) print(random_string(12)) print(random_string(12)) print(random_string(12)) #Output: avfsqkkbydlx xtpbkwjkvqzg ymmmgdvjqmmr The ability to randomly generate […]
Check if Word is Palindrome Using Recursion with Python
You can use a recursive function in Python to easily check if a word is a palindrome. def checkPalindrome(word): if len(word) < 2: return True if word[0] != word[-1]: return False return checkPalindrome(word[1:-1]) print(checkPalindrome("hello")) print(checkPalindrome("anna")) #Output: False True When working in Python, recursion and recursive functions are very useful and powerful if used correctly. One […]
Create Symbolic Link with Python os.symlink() Function
To create a symbolic link in Python, you can use the os module symlink() function. import os os.symlink("C:/Users/TheProgrammingExpert/Files/example.py","C:/temp/example.py") When working with file systems, symbolic links can be very useful for navigation if you want to add links to specific folders and directories. With Python, we can create symbolic links with the help of the os […]
Convert First Letter of String to Lowercase in Python
To convert the first letter of a string to lowercase in Python, you can use string slicing and the lower() function. string = "EXAMPLE" first_lowercase = string[0].lower() + string[1:] print(first_lowercase) #Output: eXAMPLE When working with strings in Python, the ability to be able to change and manipulate the values of those strings can be very […]
Get All Substrings of a String in Python
To get all substrings of a string in Python, the easiest way is to use list comprehension and slicing. string = "example" all_substrings = [string[i:j] for i in range(len(string)) for j in range(i + 1, len(string) + 1)] print(all_substrings) #Output: ['e', 'ex', 'exa', 'exam', 'examp', 'exampl', 'example', 'x', 'xa', 'xam', 'xamp', 'xampl', 'xample', 'a', 'am', […]
Find Least Common Multiple of Numbers Using Python
To find the least common multiple of two numbers, the easiest way is to use the equation that the product of two numbers equals the least common multiple times the greatest common divisor. def gcd(a,b): if b == 0: return a return gcd(b, a % b) def lcm(x, y): return x * y / gcd(x, […]
Using Python to Get Domain from URL
To get the domain from a URL in Python, the easiest way is to use the urllib.parse module urlparse() function and access the netloc attribute. from urlparse.parse import urlparse domain = urlparse("http://theprogrammingexpert.com/python-get-domain-from-url").netloc print(domain) #Output: theprogrammingexpert.com When working with URLs in Python, the ability to easily extract information about those URLs can be very valuable. One […]
Python gethostbyname() Function – Get IPv4 Address from Name
The Python socket module gethostbyname() function allows us get the IPv4 address from a given name (computer, server, domain, etc.). import socket host_name = socket.gethostname() IP_address_of_Computer = socket.gethostbyname(host_name) IP_address_of_Google = socket.gethostbyname("google.com") print(IP_address_of_computer) print(IP_address_of_Google) #Output: 10.0.0.220 172.217.4.46 When working with connections between different servers in Python, the ability to get the IP address of a client, […]
Using Python to Check if Number is Divisible by Another Number
To check if a number is divisible by another number, you can use the Python built in remainder operator %. If the remainder after division is 0, then the number is divisible by the number you divided by. def divisible_by(x, y): if (x % y) == 0: return True else: return False print(divisible_by(10,2)) print(divisible_by(15,6)) #Output: […]
Touch File Python – How to Touch a File Using Python
To touch a file using Python, the easiest way is with the Path.touch() function from the pathlib module. Touching a file means creating a new file or updating a timestamp of an existing file. from pathlib import Path Path("file_name.py").touch() When working with files and directories in Python, the ability to easily add, modify or remove […]
Get Public IP Address Using Python
To get the public IP address of your computer, you can use the Python socket module gethostbyname() function. import socket host_name = socket.gethostname() IP_address = socket.gethostbyname(host_name) print(IP_address) #Output: 10.0.0.220 You can also use gethostbyname() to get the IP address of a website. import socket IP_address = socket.gethostbyname("google.com") print(IP_address) #Output: 172.217.4.46 When working with connections between […]
Golden Ratio Constant phi in Python
To get the golden ratio constant phi in your Python code, the easiest way is with the equation one plus the square root of five all divided by two. phi = (1 + 5 ** 0.5) / 2 print(phi) #Output: 1.618033988749895 The golden ratio constant phi is also available in the scipy module. import scipy.constants […]
Perfect Numbers in Python
We can check if a number is a perfect number in Python easily with a simple function. A number is perfect is the divisors of a number (excluding the number itself) sum to the number. def checkPerfectNumber(n): sum_div = 0 for i in range(1, n // 2 + 1): if (n % i == 0): […]
Remove Every Nth Element from List in Python
To remove every nth element from a list in Python, the easiest way is to use slicing. def remove_every_nth(lst, n): del lst[n-1::n] return lst example = [1, 2, 3, 4, 5, 6, 7] print(remove_every_nth(example,3)) #Output: [1, 2, 4, 5, 7] When working with collections of data, the ability to easily keep or remove specific items […]
Keep Every Nth Element in List in Python
To keep every nth element in a list in Python, the easiest way is to use slicing. lst = [1, 2, 3, 4, 5, 6, 7] every_3rd = lst[::3] print(every_3rd) #Output: [1, 4, 7] If you want to create a function which will keep every nth element in a list, you can do the following: […]
Count Spaces in String in Python
In Python, we can easily count how many spaces are in a string using a loop and counting the number of spaces we find in the string. def countSpaces(string): count = 0 for char in string: if char in " ": count = count + 1 return count print(countSpaces("Hello World!")) #Output: 1 When working with […]
Get Random Letter in Python
To get a random letter from the alphabet in Python, you can use the Python random module randint() function after creating a list of the letters of the alphabet. import string from random import randint def random_letter(): alphabet = list(string.ascii_lowercase) return alphabet[randint(0,25)] print(random_letter()) print(random_letter()) print(random_letter()) #Output: y s r When working in Python, the ability […]
Get List of Letters in Alphabet with Python
To create a list of the letters of the alphabet in Python, the easiest way is to use the string module and access the pre-defined string constants ascii_lowercase, ascii_uppercase, or ascii_letters. import string print(list(string.ascii_lowercase)) print(list(string.ascii_uppercase)) print(list(string.ascii_letters)) #Output: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', […]
Ceiling Division in Python
To perform ceiling division in Python, you can define your own function and utilize the floor division operator //. def ceiling_division(x,y): return -1 * (-x // y) print(ceiling_division(11,3)) print(ceiling_division(40,9)) print(ceiling_division(1,4)) #Output: 4 5 1 You can also utilize the math module ceil() function to perform ceiling division. import math print(math.ceil(11/3)) print(math.ceil(40/9)) print(math.ceil(1/4)) #Output: 4 5 […]
Get Tomorrow’s Date as Datetime in Python
To get tomorrow’s date as a datetime in Python, the easiest way is to use the Python timedelta() function from the datetime module. from datetime import timedelta, datetime tomorrow_datetime = datetime.now() + timedelta(days=1) print(datetime.now()) print(tomorrow_datetime) #Output: 2022-05-05 16:26:40.727149 2022-05-06 16:26:40.727149 When working with data in Python, many times we are working with dates. Being able […]
Using Python to Sum the Digits of a Number
To sum the digits of a number in Python, you can use a loop which will get each digit and add them together. def sumDigits(num): sum = 0 for x in str(num): sum = sum + int(x) return sum print(sumDigits(100)) print(sumDigits(213)) #Output: 1 6 When working with numbers in Python, the ability to easily get […]
Add Minutes to Datetime Variable Using Python timedelta() Function
To add minutes to a datetime using Python, the easiest way is to use the Python timedelta() function from the datetime module. from datetime import timedelta, datetime now = datetime.now() one_minute_in_future = now + timedelta(minutes=1) sixty_minutes_in_future = now + timedelta(minutes=60) one_day_in_future = now + timedelta(minutes=1440) print(now) print(one_minute_in_future) print(sixty_minutes_in_future) print(one_day_in_future) #Output: 2022-05-05 15:45:53.655282 2022-05-05 15:46:53.655282 2022-05-05 […]
Find Magnitude of Complex Number in Python
To find the magnitude of a complex number in Python, you can create a complex object and take the absolute value of that object. c = complex(5,7) #represents the complex number 5 + 7i magnitude = abs(c) print(magnitude) #Output: 8.602325267042627 One of the reasons why Python is so awesome is that we can perform a […]
Divide Each Element in List by Scalar Value with Python
To divide a list by a scalar in Python, the easiest way is with list comprehension. list_of_numbers = [1, 5, 2, 4] print([num / 3 for num in list_of_numbers]) #Output: [0.3333333333333333, 1.6666666666666667, 0.6666666666666666, 1.3333333333333333] You can also use the Python map() function to apply a function and divide a list by a scalar. list_of_numbers = […]
Multiply Each Element in List by Scalar Value with Python
To multiply a list by a scalar in Python, the easiest way is with list comprehension. list_of_numbers = [1, 5, 2, 4] print([num * 3 for num in list_of_numbers]) #Output: [3, 15, 6, 12] You can also use the Python map() function to apply a function and multiply a list by a scalar. list_of_numbers = […]
Using Python to Replace Backslash in String
To replace backslashes in a string with Python, the easiest way is to use the Python built-in string replace() function. string_with_backslashes = r"This\is\a\string\with\backslashes." string_with_underscores = string_with_backslashes.replace("\\","_") print(string_with_underscores) #Output: This_is_a_string_with_backslashes. When working with strings in Python, being able to manipulate your variables easily is important. There are a number of built in string methods which allow […]
Using Python to Remove Apostrophe From String
You can easily remove an apostrophe from a string in Python with the Python replace() function. string_with_apostrophe = "I'm looking for the dog's collar." string_without_apostrophe = string_with_apostrophe.replace("'","") print(string_without_apostrophe) #Output: Im looking for the dogs collar. When working with strings in Python, being able to manipulate your variables easily is important. There are a number of […]
Remove Specific Word from String in Python
To remove a specific word in a string variable in Python, the easiest way is to use the Python built-in string replace() function. string_with_words = "This is a string." string_without_is = string_with_words.replace("is","") print(string_without_is) #Output: This a string. When working with strings in Python, being able to manipulate your variables easily is important. There are a […]
Find Median of List in Python
To find the median number of a list in Python, you just need to sort the list of numbers and then find the middle number. If the length of the list is odd, you take the middle number as the median. If the length of the list is even, you find the average between the […]
How to Remove Vowels from a String in Python
To remove vowels from a string in Python, the easiest way is to use a regular expression search. import re string_example = "This is a string with some vowels and other words." string_without_vowels = re.sub("[aeiouAEIOU]","",string_example) print(string_without_vowels) #Output: Ths s strng wth sm vwls nd thr wrds. You can also use a loop which will loop […]
How to Cube Numbers in Python
To cube a number in Python, the easiest way is to multiply the number by itself three times. cube_of_10 = 10*10*10 We can also use the pow() function from the math module to cube a number. import math cube_of_10 = math.pow(10,3) Finally, we can find the cube of a number in Python with the built […]
pandas interpolate() – Fill NaN Values with Interpolation in DataFrame
When working with data in pandas, you can fill NaN values with interpolation using the pandas interpolate() function. df_withinterpolation = df["col_with_nan"].interpolate(method="linear") There are many different interpolation methods you can use. In this post, you’ll learn how to use interpolate() to fill NaN Values with pandas in Python. When working with data, NaN values can be […]
Apply Function to All Elements in List in Python
To apply a function to a list in Python, the easiest way is to use list comprehension to apply a function to each element in a list. def add_one(x): return x + 1 example_list = [0, 1, 2, 3, 4, 5] print([add_one(i) for i in example_list]) #Output: [1, 2, 3, 4, 5, 6] You can […]
Using pandas resample() to Resample Time Series Data
In Python, we can use the pandas resample() function to resample time series data in a DataFrame or Series object. Resampling is a technique which allows you to increase or decrease the frequency of your time series data. Let’s say we have the following time series data. import pandas as pd import numpy as np […]
Using pandas sample() to Generate a Random Sample of a DataFrame
To sample a DataFrame with pandas in Python, you can use the sample() function. Pass the number of elements you want to extract or a fraction of items to return. sampled_df = df.sample(n=100) sampled_df = df.sample(frac=0.5) In this article, you’ll learn how to get a random sample of data in Python with the pandas sample() […]
Sign Function in Python – Get Sign of Number
In Python, there is no sign function, but it is easy to get the sign of a number by defining our own sign function. def sign_function(x): if x > 0: return 1 elif x == 0: return 0 else: return -1 print(sign_function(-10)) # Output: -1 You can also use the Math module copysign() function – […]
Sorting with Lambda Functions in Python
In Python, we can use a lambda expression with the sorted() or sort() function to sort with a function. To use lambda with sorted(), pass the lambda expression to the ‘key’ argument. lst = ["this","is","another","list","of","strings"] list_sorted_by_second_letter = sorted(lst,key=lambda x: x[1]) print(list_sorted_by_second_letter) #output: ['of', 'this', 'list', 'another', 'is', 'strings'] You can do the same for the […]
Date Format YYYYMMDD in Python
In Python, we can easily format dates and datetime objects with the strftime() function. For example, to format a date as YYYY-MM-DD, pass “%Y-%m-%d” to strftime(). import datetime currentDate = datetime.date.today() print(currentDate.strftime("%Y-%m-%d")) #Output: 2022-03-12 If you want to create a string that is separated by slashes (“/”) instead of dashes (“-“), pass “%Y/%m/%d” to strftime(). […]
Pascal’s Triangle in Python
In Python, we can easily create Pascal’s Triangle with a loop to create a multi-dimensional list for a given number of rows. def pascalsTriangle(rows): t = [] for i in range(rows): t.append([]) t[i].append(1) for j in range(1,i): t[i].append(t[i-1][j-1]+t[i-1][j]) if i != 0: t[i].append(1) return t print(pascalsTriangle(5)) #Output: [[1], [1, 1], [1, 2, 1], [1, 3, […]
Remove Duplicates from Sorted Array in Python
To remove duplicates from a sorted array in Python without using extra space, we can define a function which will loop over your list and delete any duplicates. def removeDuplicates(arr): for i in range(len(arr)-1,0,-1): if arr[i] == arr[i-1]: del arr[i] return arr sorted_list = [1,2,2,3,3,4,5,5,8,8,8,8,9,9,9] print(removeDuplicates(sorted_list)) #Output: [1, 2, 3, 4, 5, 8, 9] Another […]
Get Elapsed Time in Seconds in Python
To measure the elapsed time of a process in Python, use the time module to find the starting time and ending time, and then subtract the two times. import time starting_time = time.time() print("Process started…") print("Process ended…") ending_time = time.time() print(ending_time – starting_time) #Output: 0.0018320083618164062 When creating Python programs, the ability to easily benchmark and […]
Find All Pythagorean Triples in a Range using Python
To get all Pythagorean triples up to a given number in Python, we can use a for loop and apply the Pythagorean triplet’s square sum connection. def pythagorean_triples(num): triples = [] c, m = 0, 2 while c < num: for n in range(1, m): a = m * m – n * n b […]
Symmetric Difference of Two Sets in Python
In Python, we can find the symmetric difference of two sets easily with the set symmetric_difference() function. a = {0, 1, 2, 3, 4, 5} b = {3, 4, 5, 6, 7, 8} print(a.symmetric_difference(b)) #Output: {0, 1, 2, 6, 7, 8} You can also get the symmetric difference of two sets with the ^ operator. […]
Check if List is Subset of Another List in Python
There are a number of ways to check if a list is a subset of another list in Python. The easiest way is to convert the lists to sets and use the issubset() function. big_list = [1, 2, 3, 4, 5, 6, 7] small_list = [1, 2, 3] print(set(small_list).issubset(set(big_list)) #Output: True You can also use […]
Comparing Datetimes in Python
In Python, we can easily compare two datetimes to see which datetime is later than another with >, , operator. Below is a simple example in Python of how to compare datetimes to see which datetime is later than the other. import datetime datetime1 = datetime.datetime(2022,3,5,0,0,0) datetime2 = datetime.datetime(2022,3,8,12,30,0) print(datetime1 > datetime2) #Output: False How […]
Convert timedelta to Seconds in Python
To convert a timedelta to seconds in Python, we can use the total_seconds() function on a timedelta object. import datetime datetime1 = datetime.datetime(2022,3,5,0,0,0) datetime2 = datetime.datetime(2022,3,7,0,0,0) timedelta_object = datetime2 – datetime1 print(timedelta_object.total_seconds()) #Output: 172800.0 When working in Python, many times we need to create variables which represent dates and times. When creating and displaying values […]
Get Difference Between datetime Variables in Python
To get the difference between two times using Python, subtract two dates just like you would subtract two numbers to get a datetime.timedelta object. import datetime datetime1 = datetime.datetime(2022,3,5,0,0,0) datetime2 = datetime.datetime(2022,3,8,12,30,0) difference_d2_d1 = datetime2 – datetime1 print(difference_d2_d1) #Output: 3 days, 12:30:00 When working in Python, many times we need to create variables which represent […]
Time Difference in Seconds Between Datetimes in Python
To get the difference between two times in seconds using Python, we can use the total_seconds() function after subtracting two dates. import datetime datetime1 = datetime.datetime(2022,3,5,0,0,0) datetime2 = datetime.datetime(2022,3,7,0,0,0) difference_d2_d1 = datetime2 – datetime1 print(difference_d2_d1.total_seconds()) #Output: 172800.0 When working in Python, many times we need to create variables which represent dates and times. When creating […]
Get Month Name from Date in Python
To get the month name from a number in Python, the easiest way is with strftime() and passing “%M”. import datetime currentDate = datetime.date.today() currentMonthName = currentDate.strftime("%B") print(currentDate) print(currentMonthName) #Output: 2022-03-07 March You can also use the calendar module and the month_name() function. import calendar import datetime currentDate = datetime.date.today() currentMonthName = calendar.month_name[currentDate.month] print(currentDate) print(currentMonthName) […]
Get First Day of Month Using Python
To get the first day of the month using Python, the easiest way is to create a new date with datetime.date() and pass “1” as the third argument. import datetime currentDate = datetime.date.today() firstDayOfMonth = datetime.date(currentDate.year, currentDate.month, 1) print(currentDate) print(firstDayOfMonth) #Output: 2022-03-06 2022-03-01 When working in Python, many times we need to create variables which […]
Get Last Day of Month Using Python
To get the last day of the month using Python, the easiest way is with the timerange() function from the calendar module to get the number of days in the month, and then create a new date. import calendar import datetime currentDate = datetime.date.today() lastDayOfMonth = datetime.date(currentDate.year, currentDate.month, calendar.monthrange(currentDate.year, currentDate.month)[1]) print(currentDate) print(lastDayOfMonth) #Output: 2022-03-06 2022-03-31 […]
Get Days in Month Using Python
To get the days in the month using Python, the easiest way is with the timerange() function from the calendar module to get the number of days in the month. import calendar import datetime currentDate = datetime.date.today() daysInMonth= calendar.monthrange(currentDate.year, currentDate.month)[1] print(currentDate) print(daysInMonth) #Output: 2022-03-06 31 When working in Python, many times we need to create […]
Get Day of the Year with Python
When using Python, there are a number of ways to get the day of the year in Python. The easiest way to use datetime.timetuple() to convert your date object to a time.struct_time object then access ‘tm_yday’ attribute. import datetime currentDate = datetime.date.today() day_of_year = currentDate.timetuple().tm_yday print(currentDate) print(day_of_year) #Output: 2022-03-06 65 You can also get the […]
Print Object Attributes in Python using dir() Function
To print an object’s attributes using Python, the easiest way is with the dir() function. list_object = [1, 2, 3] print(dir(list_object)) #Output: ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', […]
Remove Time from Datetime in Python
To remove the time from a datetime object in Python, convert the datetime to a date using date(). import datetime currentDateTime = datetime.datetime.now() currentDateWithoutTime = currentDateTime.date() print(currentDateTime) print(currentDateWithoutTime) #Output: 2022-03-05 15:33:11.283729 2022-03-05 You can also use strftime() to create a string from a datetime object without the time. import datetime currentDateTime = datetime.datetime.now() currentDateWithoutTime = […]
Get Current Year in Python
When using Python, there are a number of ways to get the current year in Python. The easiest way to get the current year is to use the datetime.today() function from the datetime module and access the “year” attribute. import datetime currentDate = datetime.date.today() print(currentDate.year) #Output: 2022 You can also use the strftime function to […]
Sort Series in pandas with sort_values() Function
When working with series from the pandas module in Python, you can easily sort series using the sort_values() function. s = pd.Series([11, 5, 30, 25, 14]) print(s.sort_values()) #Output: 1 5 0 11 4 14 3 25 2 30 dtype: int64 When working with data, it is very useful to be able to sort data in […]
Cartesian Product of Two Lists in Python
In Python, we can get the Cartesian product of two lists easily. The easiest way to obtain the Cartesian product of two lists is with list comprehension. list1 = ["a", "b", "c"] list2 = [1, 2, 3] cartesian_product = [(x,y) for x in list1 for y in list2] print(cartesian_product) #Output: [('a', 1), ('a', 2), ('a', […]
Zip Two Lists in Python
In Python, we can zip two lists together easily with the zip() function. You can create new lists of tuples or dictionaries with the zip() function. list1 = ["this","is","a","list"] list2 = [1, 2, 3, 4] print(list(zip(list1, list2))) print(dict(zip(list1, list2))) #Output: [('this', 1), ('is', 2), ('a', 3), ('list', 4)] {'this': 1, 'is': 2, 'a': 3, 'list': […]
How to Slice a Dictionary in Python
With Python, we can easily slice a dictionary to get just the key/value pairs we want. To slice a dictionary, you can use dictionary comprehension. dictionary = {"apples":3, "bananas":4, "pears":5, "lemons":10, "tomatoes": 7} keys_for_slicing = ["apples","lemons"] sliced_dict = {key: dictionary[key] for key in keys_for_slicing } print(sliced_dict) #Output: {'apples': 3, 'lemons': 10} In Python, dictionaries are […]
Truncate String in Python with Slicing
In Python, the easiest way to truncate a string is with slicing. With slicing, you can truncate strings by any number of characters. string = "This is a string variable" string_without_last_three_chars = string[:-3] print(string_without_last_three_chars) #Output: This is a string varia When using string variables in Python, we can easily perform string manipulation to change the […]
Python tostring method – Convert an Object to String with str() Function
In Python, to convert a variable to a string, you can use the str() function. There is no tostring() method like in other languages. a = 3 a_as_str = str(a) print(a, type(a)) print(a_as_str, type(a_as_str)) #Output: 3 <class 'int'> 3 <class 'str'> When using various programming languages, the ability to be able to convert variables from […]
List of Turtle Shapes in Python
When using the turtle module in Python, there are six different turtle shapes you can use to change the shape of your turtle. The list of turtle shapes includes the following shapes. turtle_shapes_list = ["arrow","turtle","circle","square","triangle","classic"] To change the shape of your turtle, call the shape() function. import turtle t = turtle.Turtle() t.shape("turtle") The turtle module […]
Python dirname – Get Directory Name of Path using os.path.dirname()
The Python dirname() function is very useful for getting the directory name of a given path. import os print(os.path.dirname("/Home/Documents/example.py") #Output: /Home/Documents When working with file systems, it can be useful to be able to get the directory name and path of a file. The Python os module provides us with a number of great functions […]
Replace Values in Dictionary in Python
When working with dictionaries in Python, to replace a value in a dictionary, you can reassign a value to any key by accessing the item by key. dictionary = {"apples":3, "bananas":4, "pears":5} dictionary["apples"] = 6 print(dictionary) #Output: {"apples":6, "bananas":4, "pears":5} In Python, dictionaries are a collection of key/value pairs separated by commas. When working with […]
How to Concatenate Tuples in Python
We can easily concatenate tuples in Python. To concatenate the elements of two tuples, you can use the Python + operator. tuple1 = (1, 2, 3) tuple2 = (4, 5) print(tuple1 + tuple2) #Output: (1, 2, 3, 4, 5) You can also use the Python sum() function to concatenate tuples. tuple1 = (1, 2, 3) […]
Add Tuple to List in Python
In Python, we can easily add a tuple to a list with the list extend() function. list_of_numbers = [0, 1, 2, 3] tuple_of_numbers = (4, 5) list_of_numbers.extend(tuple_of_numbers) print(list_of_numbers) #Output: [0, 1, 2, 3, 4, 5] You can also use the += operator to append the items of a tuple to a list in Python. list_of_numbers […]
Print Multiple Variables in Python
In Python, we can print multiple variables easily with the print() function. Just pass each variable to print() separated by commas to print multiple variables on one line. x = 0 y = 1 z = 2 print(x,y,z) #Output: 0 1 2 In Python, when writing programs, being able to check the value of certain […]
Creating a Random Color Turtle in Python
In Python when using the turtle module, we can easily create a random color turtle with the help of the randint() function. import turtle from random import randint turtle.colormode(255) t = turtle.Turtle() t.color(randint(0,255),randint(0,255),randint(0,255)) The Python turtle module provides us with many functions which allow us to add color to the shapes we draw. There are […]
Sorting a List of Tuples by Second Element in Python
In Python, we can sort a list of tuples by the second element of each tuple easily. The easiest way to sort a list of tuples by the second element is using the sort() function and a lambda expression. list_of_tuples = [('apple', 3), ('pear', 5), ('banana', 1), ('lime', 4)] list_of_tuples.sort(key=lambda t: t[1]) print(list_of_tuples) #Output: [('banana', […]
Sort List of Tuples in Python
In Python, we can sort a list of tuples easily. The easiest way to sort a list of tuples is using the sort() function. list_of_tuples = [('apple', 3), ('pear', 5), ('banana', 1), ('lime', 4)] list_of_tuples.sort() print(list_of_tuples) #Output: [('apple', 3), ('banana', 1), ('lime', 4), ('pear', 5)] You can also use sorted to sort a list of […]
Python Split Tuple into Multiple Variables
In Python, you can split tuples into multiple variables with tuple unpacking. You can unpack tuples with variable names separated by commas. x, y, z = (0, 1, 2) print(x) print(y) print(z) #Output: 0 1 2 In Python, tuples are a collection of objects which are ordered and mutable. When working with tuples, it can […]
How to Split a String in Half Using Python
In Python, to split a string in half, the easiest way is with floor division and string slicing. def splitString(string): first_half = string[0:len(string)//2] second_half = string[len(string)//2:] return [first_half,second_half] print(splitString("split me in half")) #Output: ['split me', ' in half'] You can also use the slice function to build a slice and then split the string in […]
Combine Sets in Python
In Python, we can easily combine sets by adding two sets together. The easiest way to combine sets is to use |= in your Python code. a = {0, 1, 2, 3, 4} b = {4, 5, 6, 7, 8} a |= b print(a) #Output: {0, 1, 2, 3, 4, 5, 6, 7, 8} You […]
Python Split List into N Sublists
In Python, we can split a list into n sublists a number of different ways. Given a length, or lengths, of the sublists, we can use a loop, or list comprehension to split a list into n sublists. list_of_numbers = [0,1,2,3,4,5] def getSublists(lst,n): subListLength = len(lst) // n list_of_sublists = [] for i in range(0, […]
Check if All Elements in Array are Equal in Python
With Python, we can check if all elements in a list are equal by converting the list to a set and checking if the set has length 1. def checkAllElementsEqual(lst): return len(set(lst)) == 1 print(checkAllElementsEqual([0,1,2,3,4])) print(checkAllElementsEqual([0,0,0,0,0])) #Output: False True When working with collections of data in a Python program, it’s possible you want to check […]
How to Multiply All Elements in List Using Python
In Python, we can easily multiply all elements in a list. The easiest way to get the product of all items of a list is with a loop. def multiplyNumbers(lst): product = 1 for x in lst: product = product * x return product print(multiplyNumbers([9,3,2,4]) #Output: 216 You can also use a lambda expression combined […]
Check if Set Contains Element in Python
To check if a set contains a specific element in Python, you can use the Python in operator. set_of_numbers = {0,1,2,3,4} if 3 in set_of_numbers: print("3 is in the set of numbers!") else: print("3 is not in the set of numbers!") #Output: 3 is in the set of numbers If you want to check if […]
Swap Two Values of Variables in Python
With Python, we can easily swap two values between variables. The easiest way is to use tuple unpacking. x = 2 y = 3 x, y = y, x print(x) print(y) #Output: 3 2 You can also use a temporary variable to swap the values of two variables. x = 2 y = 3 temp_var […]
Using Python to Find Second Largest Value in List
In Python, we can find the second largest value in a list easily using a simple function and a for loop. list_of_numbers = [2, 1, 9, 8, 6, 3, 1, 0, 4, 5] def findSecondLargest(lst): firstLargest = max(lst[0],lst[1]) secondLargest = min(lst[0],lst[1]) for i in range(2,len(lst)): if lst[i] > firstLargest: secondLargest = firstLargest firstLargest =lst[i] elif […]
Using Python to Find Second Smallest Value in List
In Python, we can find the second smallest value in a list easily using a simple function and a for loop. list_of_numbers = [2, 1, 9, 8, 6, 3, 1, 0, 4, 5] def findSecondSmallest(lst): firstSmallest = min(lst[0],lst[1]) secondSmallest = max(lst[0],lst[1]) for i in range(2,len(lst)): if lst[i] < firstSmallest: secondSmallest = firstSmallest firstSmallest = lst[i] […]
Find Index of Maximum in List Using Python
In Python, we can easily find the index of the maximum in a list of numbers. The easiest way to get the index of the maximum in a list with a loop. list_of_numbers = [2, 1, 9, 8, 6, 3, 1, 0, 4, 5] def maxIndex(lst): index = [0] max = lst[0] for i in […]
Find Index of Minimum in List Using Python
In Python, we can easily find the index of the minimum in a list of numbers. The easiest way to get the index of the minimum in a list with a loop. list_of_numbers = [2, 1, 9, 8, 6, 3, 1, 0, 4, 5] def minIndex(lst): index = [0] min = lst[0] for i in […]
Python Get Operating System Information with os and platform Modules
In Python, the os and platform modules have many useful functions which allow us to get operating system information easily. import os import platform print(os.name) print(platform.system()) print(platform.release()) print(platform.platform()) #Output: nt Windows 10 Windows-10-10.0.22000-SP0 In Python, the os and platform modules have provide us with many useful functions which allow us to get information about the […]
Using if in Python Lambda Expression
In Python, we can use if statements to add conditions our lambda expressions. We can create if, elif, and else blocks in a Python lambda expression easily. lambda_expression = lambda x: True if x > 0 else False In Python, lambda expressions are very useful for creating anonymous functions which can be applied on variables […]
Fibonacci Sequence in Python with for Loop
With Python, we can easily get a Fibonacci sequence with a for loop. The Fibonacci sequence first two terms are 0 and 1, and each subsequent term is the sum of the last two terms. def fibonacci(n): sequence = [] if n == 1: sequence = [0] else: sequence = [0,1] for i in range(1, […]
Python turtle Colors – How to Color and Fill Shapes with turtle Module
The Python turtle module provides us with many functions which allow us to add color to the shapes we draw. You can use any valid Tk color name with turtle module, as well as RGB colors. Some colors include: colors = ['yellow', 'cyan', 'red', 'light blue', 'pink', 'blue', 'purple', 'green', 'orange'] Below is a brief […]
Changing Python Turtle Size with turtlesize() Function
When using the turtle module in Python, we can change the turtle size with the turtlesize() function to get a bigger or smaller turtle. import turtle t = turtle.Turtle() t.turtlesize(5) If you’d instead like to change the pen size, you can use the pensize() function. import turtle t = turtle.Turtle() t.pensize(3) The turtle module in […]
Change Python Turtle Background Color with screensize() Function
When using the turtle module in Python, we can change the turtle screen background color with the screensize() function. import turtle turtle.screensize(bg="red") The turtle module in Python allows us to create graphics easily in our Python code. We can use the turtle module to make all sorts of graphics in Python. For example, we can […]
Adjusting Python Turtle Screen Size with screensize() Function
When using the turtle module in Python, we can change the turtle screen size dimensions with the screensize() function. import turtle turtle.screensize(canvwidth=550, canvheight=350) The turtle module in Python allows us to create graphics easily in our Python code. We can use the turtle module to make all sorts of graphics in Python. For example, we […]
Changing Python Turtle Speed with speed() Function
When working with the turtle module in Python, to change the speed of a turtle, you can use the Python turtle speed() function. import turtle t = turtle.Turtle() t.speed(5) The turtle module in Python allows us to create graphics easily in our Python code. When working with our turtle, sometimes it makes sense to want […]
How to Hide Turtle in Python with hideturtle() Function
When using the turtle Module in Python, we can hide the turtle by using the hideturtle() function. import turtle t = turtle.Turtle() def draw_circle(radius): t.circle(radius) draw_circle(100) t.hideturtle() The turtle module in Python allows us to create graphics easily in our Python code. We can use the turtle module to make all sorts of shapes in […]
How to Clear Turtle Screen in Python with clear() Function
When using the turtle Module in Python, we can clear the turtle screen by using the clear() function. import turtle t = turtle.Turtle() def draw_square(length): for i in range(0,4): t.forward(length) t.right(90) draw_square(100) t.clear() The turtle module in Python allows us to create graphics easily in our Python code. We can use the turtle module to […]
Using Python turtle Module to Draw Square
To draw a square in Python, we can use the Python turtle module. import turtle t = turtle.Turtle() def draw_square(length): for i in range(0,4): t.forward(length) t.right(90) draw_square(100) The turtle module in Python allows us to create graphics easily in our Python code. We can use the turtle module to make all sorts of shapes in […]
Draw Circle in Python Using turtle circle() Function
To draw a circle in Python, we can use the circle() function from the Python turtle module. import turtle t = turtle.Turtle() def draw_circle(radius): t.circle(radius) draw_circle(100) The turtle module in Python allows us to create graphics easily in our Python code. We can use the turtle module to make all sorts of shapes in Python. […]
Draw Rectangle in Python Using turtle Module
To draw a rectangle in Python, we can use the Python turtle module. import turtle t = turtle.Turtle() def draw_rectangle(length, height): for i in range(0,4): if i % 2 == 0: t.forward(length) t.right(90) else: t.forward(height) t.right(90) draw_rectangle(100, 200) The turtle module in Python allows us to create graphics easily in our Python code. We can […]
How to Draw a Triangle in Python Using turtle Module
To draw a triangle in Python, we can use the Python turtle module. import turtle t = turtle.Turtle() def draw_triangle(side_length): for i in range(0,3): t.forward(side_length) t.right(120) draw_triangle(100) The turtle module in Python allows us to create graphics easily in our Python code. We can use the turtle module to make all sorts of shapes in […]
Reverse Words in a String Python
In Python, we can easily reverse words in a string in Python using the Python split(), reverse() and join() functions. def reverseWords(string): words = string.split() words.reverse() return " ".join(words) print(reverseWords("this is a string with words")) #Output: words with string a is this You can also use the split() function, slicing, and the join() function to […]
Difference Between // and / When Dividing Numbers in Python
In Python, when doing division, you can use both // and / to divide numbers. // means floor or integer division, and / means floating point division. print(10/3) print(10//3) #Output: 3.333333333333335 3 In Python, we can perform division of numbers in different ways. You can use both // and / to divide numbers The difference […]
e in Python – Using Math Module to Get Euler’s Constant e
To get the value of Euler’s Constant e in Python, the easiest way is to use the Python math module constant e. math.e returns the value 2.718281828459045. import math print(math.e) #Output: 2.718281828459045 In Python, we can easily get the value of e for use in various equations and applications with the Python math module. To […]
Euclidean Algorithm and Extended Euclidean Algorithm in Python
The Euclidean Algorithm is a method for calculating the greatest common divisor (GCD) of two integers. With Python, we can use recursion to calculate the GCD of two integers with the Euclidean Algorithm. def euclideanAlgorithm(a,b): if b == 0: return a return euclideanAlgorithm(b, a % b) print(euclideanAlgorithm(10,25)) #Output: 5 We can also use Python to […]
math gcd Python – Find Greatest Common Divisor with math.gcd() Function
With Python, we can calculate the greatest common divisor of two numbers with the math gcd() function. import math print(math.gcd(10,25)) #Output: 5 The Python math module has many powerful functions which make performing certain calculations in Python very easy. One such calculation which is very easy to perform in Python is finding the greatest common […]
Break Out of Function in Python with return Statement
To break out of a function in Python, we can use the return statement. The Python return statement can be very useful for controlling the flow of data in our Python code. def doStuff(): print("Here before the return") return print("This won't print") doStuff() #Output: Here before the return When working with functions in Python, it […]
rfind Python – Find Last Occurrence of Substring in String
In Python, the string rfind() function is very useful. We can use the rfind() Python function to find the last occurrence in a string of a character or substring. string_variable = "This is a string variable we will search." pos_of_last_a = string_variable.rfind("a") pos_of_last_w = string_variable.rfind("w") print(pos_of_last_a) print(pos_of_last_w) #Output: 36 29 When working with string variables […]
How to Create Array from 1 to n in Python
To create a list with the numbers from 1 to n using Python, we can use the range() function in a custom Python function. def listFrom1toN(n): return list(range(1,n+1)) print(listFrom1toN(13)) #Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] You can also use a loop to create a list from 1 […]
Convert List to Set with Python
In Python, the easiest way to convert a list to a set is using the Python set() function. l = [0,1,2,3] converted_to_set = set(l) print(converted_to_set) #Output: {0,1,2,3} If your list has duplicates, set() will remove them. l = [0,1,2,3,0,0,3] converted_to_set = set(l) print(converted_to_set) #Output: {0,1,2,3} When working with collections of items in Python, it can […]
How to Repeat a Function in Python
To repeat a function in Python, the easiest way is with a for loop. def multiplyBy2(num): return num*2 x = 2 for i in range(0,4): x = multiplyBy2(x) print(x) #Output: 32 You can also use a while loop to repeat a function in Python. def multiplyBy2(num): return num*2 x = 2 while x < 30: […]
Intersection of Two Lists in Python
In Python, the easiest way to get the intersection of two lists is by using list comprehension to identify the values which are in both lists. list_1 = [5,3,8,2,1] list_2 = [9,3,4,2,1] intersection_of_lists = [x for x in list_1 if x in list_2] print(intersection_of_lists) #Output: [3, 2, 1] If you want to find the intersection […]
Union of Lists in Python
In Python, the easiest way to get the union of two lists is by using the + operator to add the two lists together. You can then remove the duplicates from the result by converting it to a set, and then converting that set back to a list. list_1 = [5,3,8,2,1] list_2 = [9,3,4,2,1] union_of_lists […]
Multiple Condition if Statements in Python
In Python, if statements are very useful to control the flow of your program. We can easily define an if statement with multiple conditions using logical operators. num = 5 if num < 10 and num % 4 != 0: print(num) #Output: 5 In Python, if statements allow us to control the flow of data […]
Remove Element from Set in Python
In Python, we can easily remove an element from a set in a number of ways. The easiest way to remove an element from a set is with the remove() function. set_with_elements = {"whale","dog","cat"} set_with_elements.remove("dog") print(set_with_elements) #Output: {"whale","cat"} You can also use the discard() function to remove items from a set in Python. set_with_elements = […]
Multiple Condition While Loops in Python
In Python, while loops are very useful to loop over a collection of data. We can easily define a while loop with multiple conditions using logical operators. count = 1 while count < 10 and count % 4 != 0: print(count) count = count + 1 #Output: 1 2 3 In Python, loops allow us […]
How to Rotate a List in Python
In Python, the easiest way to rotate items in a list is with the Python list pop(), insert(), and append() functions. lst = [0,1,2,3] #rotated backwards (to left) lst.append(lst.pop(0)) print(lst) lst= [0,1,2,3] #rotated forward (to right) lst.insert(0,lst.pop()) print(lst) #Output: [1,2,3,0] [3,0,1,2] You can also use the deque() data structure from the Python collections module to […]
Shift Values in a List Using Python
In Python, the easiest way to shift values in a list is with the Python list pop(), insert(), and append() functions. list = [0,1,2,3] #shifted backwards (to left) list.append(list.pop(0)) print(list) list = [0,1,2,3] #shifted forward (to right) list.insert(0,list.pop()) print(list) #Output: [1,2,3,0] [3,0,1,2] You can also use the deque() data structure from the Python collections module […]
Using Python to Repeat Characters in String
In Python, we can easily repeat characters in string as many times as you would like. The easiest way to repeat each character n times in a string is to use comprehension and the Python * operator. string = "string" n = 5 repeated_characters = ''.join([character*n for character in string]) print(repeated_characters) #Output: ssssstttttrrrrriiiiinnnnnggggg You can […]
Repeat String with * Operator in Python
In Python, we can easily repeat a string as many times as you would like. The easiest way to repeat a string n times is to use the Python * operator. repeated_string = "string" * 3 print(repeated_string) #Output: stringstringstring You can also repeat a string separated by a certain separator. string = "string" separator = […]
Get First Key and Value in Dictionary with Python
In Python, there are a few different ways we can get the first key/value pair of a dictionary. The easiest way is to use the items() function, convert it to a list, and access the first element. dictionary = { "key1":"This", "key2":"is", "key3":"a", "key4":"dictionary." } first_item = list(dictionary.items())[0] print("The first item of the dictionary has […]
Loop Through Files in Directory Using Python
In Python, we can loop through files in a directory easily with the listdir() function from the Python os module. import os path = r"\examples" for x in os.listdir(path): print(os.path.join(path,x)) #Ouput: \examples\code1.py \examples\code2.py Note, the listdir() function returns a list of all names in a directory. To just get all files, you can check each […]
Count Number of Keys in Dictionary in Python
To find the number of keys in a dictionary in Python, the easiest way is to use the Python dictionary keys() function to get a list of the keys in a dictionary, and then get the length of that list with len(). dictionary = { "key1":"This", "key2":"is", "key3":"a", "key4":"dictionary." } number_of_keys_in_dictionary = len(dictionary.keys()) print(number_of_keys_in_dictionary) #Output: […]
Python Check if Float is a Whole Number
The easiest way to check if a number is a whole number in Python is using the is_integer() function. print((2.0).is_integer()) print((2.01).is_integer()) #Output: True False You can also check if the number minus the integer conversion of the number is equal to 0. print(2.0 – int(2.0) == 0) print(2.01 – int(2.01) == 0) #Output: True False […]
Python Prepend to List with insert() Function
In Python, the easiest way to prepend an item to a list is with the Python list insert() function. list = [1,2,9,0,1,3] list.insert(0,2) #Output: [2,1,2,9,0,1,3] You can also use the deque appendleft function to prepend an item to a list. from collections import deque list = [1,2,9,0,1,3] dequelist = deque(list) dequelist.appendleft(2) print(list(dequelist)) #Output: [2,1,2,9,0,1,3] In […]
Python Random Uniform – Generate Random Numbers Uniformly in Range
In Python, you can use the uniform() function from the Python random module to generate random numbers uniformly in a range. import random for x in range(0,5): print(random.uniform(0,10)) #Output: 9.142756405376938 4.285772552410724 8.395316881379259 2.3655937997142242 3.451488748786483 When working with data, it can be very useful to generate random numbers to be able to perform simulations or get […]
Count Number of Files in Directory with Python
In Python, we can count the number of files in a directory easily with the listdir() function from the Python os module. import os print(len(os.listdir(r"\examples"))) #Ouput: 5 Note, the listdir() function returns a list of all names in a directory. To just get all files, you can check each name with the isdir() function. import […]
How to Capitalize the First Letter of Every Word in Python
In Python, we can capitalize the first letter of every word in a string easily with the help of slicing, Python split() function, and the Python upper() function. string = "this is a string with some words" def capitalizeFirstLetter(string): new_strings = [] for x in string.split(" "): new_strings.append(x[0].upper() + x[1:]) return " ".join(new_strings) print(capitalizeFirstLetter(string)) #Output: […]
How to Remove All Occurrences of a Character in a List Using Python
In Python, we can remove all occurrences of a character in a list by looping over each item in the list, and using the replace() function. list_of_strings = ["This","is","a","list","of","strings","and","we","will","remove","certain","characters"] def removeCharFromList(list, char): for i in range(0,len(list)): list[i] = list[i].replace(char,"") return list print(removeCharFromList(list_of_strings,"a")) #Output: ['This', 'is', '', 'list', 'of', 'strings', 'nd', 'we', 'will', 'remove', 'certin', 'chrcters'] […]
How to Check if Variable Exists in Python
Checking if a variable exists in Python is easy. To check if a variable exists, the easiest way is with exception handling. try: print(variable) except NameError: print("variable doesn't exist") #Output: variable doesn't exist. You can use the Python globals() functions to check if a variable exists globally. variable = "this is a variable" if 'variable' […]
Print Time Elapsed in Python
In Python, the easiest way to print the time a program takes is with the Python time module. Below shows how to print time elapsed using Python. import time start = time.time() for i in range(100): x = 1 end = time.time() elapsed_time = end-start print("elapsed time in seconds: " + elapsed_time ) #Output: elapsed […]
How to Iterate through a Set Using Python
In Python, iterating through sets can be done in many ways. The easiest way to iterate through a set in Python is with a loop. set = {1,2,3} for x in set: print x #Output: 1 2 3 You can also use set comprehension to iterate through a set. set = {1,2,3} output = [print(x) […]
Reverse String with Recursion in Python
In Python, we can reverse a string with recursion using a recursive function. string = "Hello" def reverse_string(string): if len(string) == 1: return string return reverse_string(string[1:]) + string[0:1] print(reverse_string(string)) #Output: olleH When using string variables in Python, we can easily perform string manipulation to change the values or order of the characters in our string. […]
Reverse a List in Python Without Reverse Function
In Python, there are many ways we can reverse a list. While we can use the list reverse() function, there are other ways to reverse a list in Python without the reverse() function. The easiest way to reverse a list in Python without using reverse() is with slicing. lst = [1,2,3,4] lst = lst[::-1] print(lst) […]
Check if a Number is Divisible by 2 in Python
In Python, we can check if a number is divisible by 2 very easily with the Python built in remainder operator %. If the remainder of a number after dividing by 2 is 0, then the number is divisible by 2. def isDivisibleBy2(num): if (num % 2) == 0: return True else: return False print(isDivisibleBy2(10)) […]
Remove Parentheses from String Using Python
To remove parentheses from string using Python, the easiest way is to use the Python sub() function from the re module. import re string_with_parentheses = "(This is )a (string with parentheses)" string_without_parentheses = re.sub(r"[\(\)]",'',string_with_parentheses) print(string_without_parentheses) #Output: This is a string with parentheses If your parentheses are on the beginning and end of your string, you […]
Remove Brackets from String Using Python
To remove brackets from string using Python, the easiest way is to use the Python sub() function from the re module. import re string_with_brackets = "[This is ]a [string with brackets]" string_without_brackets = re.sub(r"[\[\]]",'',string_with_brackets) print(string_without_brackets) #Output: This is a string with brackets If you want to get rid of square brackets and curly brackets, you […]
Using Python to Remove Commas from String
To remove commas from a string using Python, the easiest way is to use the Python replace() function. string_with_commas = "This, is, a, string, with, commas." string_without_commas = string_with_commas.replace(",","") print(string_without_commas) #Output: This is a string with commas. You can also use a regular expression to remove quotes from a string. import re string_with_commas = "This, […]
Using Python to Replace Multiple Spaces with One Space in String
To replace multiple spaces with one space using Python, the easiest way is to use the Python sub() function from the re module. import re string_multiple_spaces = "This is a string with some multiple spaces." string_single_space = re.sub('\s+',' ',string_multiple_spaces) print(string_single_space) #Output: This is a string with some multiple spaces. Another method to replace multiple spaces […]
Using Python to Remove Quotes from String
To remove quotes from a string using Python, the easiest way is to use the Python replace() function. You can remove single and double quotes using replace(). string_single_quotes = "This' is' a' string' with' quotes." string_double_quotes = 'This" is" a" string" with" quotes.' string_without_single = string_single_quotes.replace("'","") string_without_double = string_double_quotes.replace('"',"") print(string_without_single) print(string_without_double) #Output: This is a […]
Python Delete Variable – How to Delete Variables with del Keyword
In Python, we can easily delete a variable with the del keyword. The del keyword deletes variables in your Python code. string = "this is a string" del string print(string) #Output: Error: string is not defined When working in Python, sometimes it makes sense to be able to delete a variable or delete multiple variables […]
Python Destroy Object – How to Delete Objects with del Keyword
In Python, we can destroy an object with the del keyword. The del keyword deletes objects in your Python code. string = "this is a string" del string print(string) #Output: Error: string is not defined When working in Python, sometimes it makes sense to be able to destroy an object or delete a variable in […]
Remove First and Last Character from String Using Python
To remove the first and last character from a string in Python, the easiest way is to use slicing. string = "This is a string variable" string_without_first_last_char = string[1:-1] print(string_without_first_last_char) #Output: his is a string variabl When using string variables in Python, we can easily perform string manipulation to change the value of the string […]
Using Python to Remove Last Character from String
To remove the last character from a string in Python, the easiest way is with slicing. string = "This is a string variable" string_without_last_char = string[:-1] print(string_without_last_char) #Output: This is a string variabl You can also use the Python string rstrip() function. string = "This is a string variable" string_without_last_char = string.rstrip(string[-1]) print(string_without_last_char) #Output: This […]
Using Python to Remove First Character from String
To remove the first character from a string in Python, the easiest way is with slicing. string = "This is a string variable" string_without_first_char = string[1:] print(string_without_first_char) #Output: his is a string variable When using string variables in Python, we can easily perform string manipulation to change the value of the string variables. One such […]
Remove All Instances of Value from List in Python
To remove all instances of a value from a list using Python, the easiest way is to use list comprehension. list_of_numbers = [1,2,3,4,1,2,1,4,3,2] list_without_1 = [x for x in list_of_numbers if x != 1] print(list_without_1) #Output: [2,3,4,2,4,3,2] You can also use the Python filter() function. list_of_numbers = [1,2,3,4,1,2,1,4,3,2] list_without_1 = list(filter(lambda x: x != 1, […]
Remove Last Element from List Using Python
In Python, we can remove the last element from a list easily – there are many ways to remove the last item from a list using Python. The easiest way to remove the last element from a list is with slicing. list = [1,2,9,0,1,3] list_without_last_element = list[:-1] print(list_without_last_element) #Output: [1,2,9,0,1] Another method to remove the […]
Python Remove First Element from List
In Python, we can remove the first element from a list easily – there are many ways to remove the first item from a list using Python. The easiest way to remove the first element from a list is with slicing. list = [1,2,9,0,1,3] list_without_first_element = list[1:] print(list_without_first_element) #Output: [2,9,0,1,3] Another method to remove the […]
Get First Character of String in Python
To get the first character of a string using Python, the easiest way is to use indexing and access the “0” position of the string. string = "This is a string." first_character = string[0] print(first_character) #Output: T When working with strings, it can be valuable to be able to easily filter and get only specific […]
How to Remove NaN from List in Python
To remove NaN from a list using Python, the easiest way is to use the isnan() function from the Python math module and list comprehension. from math import nan, isnan list_with_nan= [0, 1, 3, nan, nan, 4, 9, nan] list_without_nan = [x for x in list_with_nan if isnan(x) == False] print(list_without_nan) #Output: [0, 1, 3, […]
Python Get First Word in String
In Python, we can easily get the first word in a string. To do so, we can use the Python split() function and then access the first element of the list of words. string = "This is a string with words." first_word = string.split(" ")[0] #Output: This When working with strings in our Python code, […]
Get Last Character in String in Python
To get the last character in a string using Python, the easiest way is to use indexing and access the “-1” position of the string. string = "This is a string." last_character = string[-1] print(last_character) #Output: . When working with strings, it can be valuable to be able to easily filter and get only specific […]
Python Check if Object Has Attribute
Using Python, the easiest way to check if object has an attribute is to use the Python hasattr() function. if hasattr(obj, "upper"): print("Object has attribute upper!") else: print("Object doesn't have attribute upper!") We can also use exception handling to see if an object has an attribute in Python. try: obj.upper() print("Object has attribute upper!") except […]
Creating a List of Zeros in Python
In Python, we can easily create a list of zeros. The easiest way to create a list of zeros only is to use the Python * operator. list_of_zeros = [0] * 10 print(list_of_zeros) #Output: [0,0,0,0,0,0,0,0,0,0] A second way to make a list of zeros in Python is to use a for loop. list_of_zeros = list(0 […]
Create List of Odd Numbers in Range with Python
To create a list with all odd numbers in a range using Python, we can use the range() function in a custom Python function. def listOfOddNumbers(a,b): if a % 2 == 0: a = a + 1 odds = list(range(a,b,2)) return odds print(listOfOddNumbers(1,13)) print(listOfOddNumbers(2,10)) #Output: [1, 3, 5, 7, 9, 11] [3, 5, 7, 9] […]
Using Python to Get and Print First N Items in List
In Python, we can easily get and print the first n items of a list. To do so, we can use slicing and then use a loop to print each item. Below is a simple example showing how to print the first 10 items in a list. list = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] for x in list[:10]: print(x) […]
Python Print List – Printing Elements of List to the Console
In Python, we can print a list easily. We can use loops, the Python join() function, or the Python * operator to print all elements of a list. The first example shows how to print a list using a loop. list = ["This","is","a","list","of","strings"] for x in list: print(x) #Output: This is a list of strings […]
Using Python to Split a Number into Digits
In Python, there are a number of ways we can split a number into digits. The easiest way to get the digits of an integer is to use list comprehension to convert the number into a string and get each element of the string. def getDigits(num): return [int(x) for x in str(num)] print(getDigits(100)) print(getDigits(213)) #Output: […]
Count Letters in Word in Python
In Python, we can easily count the letters in a word using the Python len() function and list comprehension to filter out characters which aren’t letters. def countLetters(word): return len([x for x in word if x.isalpha()]) print(countLetters("Word.")) print(countLetters("Word.with.non-letters1")) #Output: 4 18 This is equivalent to looping over all letters in a word and checking if […]
Get First Digit in Number Using Python
In Python, there are a number of ways we can get the first digit of a number. The easiest way to get the first digit of a number is to convert it to a string and access the first element. def getFirstDigit(num): return str(num)[0] print(getFirstDigit(100)) print(getFirstDigit(213)) #Output: 1 2 The second way is we can […]
How to Check if a Letter is in a String Using Python
In Python, we can easily check if a letter is in a string using the Python in operator. def containsLetter(string, letter): return letter in string print(containsLetter("Hello World!", "H")) print(containsLetter("Hello World!", "z")) #Output: True False When working with strings, it can be useful to know if a certain character is in a string variable. In Python, […]
Check if String Contains Only Certain Characters in Python
In Python, we can easily check if a string contains certain characters using a for loop and check individually if each character is one of those characters or not. def containsCertainChars(string, chars): for char in string: if char in chars: return True return False print(containsCertainChars("Hello World!", "H")) print(containsCertainChars("Hello World!", "olz")) print(containsCertainChars("Hello World!", "z")) #Output: True […]
How to Check if String Contains Lowercase Letters in Python
In Python, we can check if a string contains lowercase characters by checking each letter to see if that letter is lowercase in a loop. def checkStrContainsLower(string): for x in string: if x == x.lower(): return True return False print(checkStrContainsLower("ALL THE LETTERS ARE UPPERCASE")) print(checkStrContainsLower("We Have some uppercase Letters in this One.")) #Output: False True […]
How to Check if String Contains Uppercase Letters in Python
In Python, we can check if a string contains uppercase characters by checking each letter to see if that letter is uppercase in a loop. def checkStrContainsUpper(string): for x in string: if x == x.upper(): return True return False print(checkStrContainsUpper("all letters here are lowercase")) print(checkStrContainsUpper("We Have some uppercase Letters in this One.")) #Output: False True […]
Get Last N Elements of List in Python
To get the last n elements of a list using Python, the easiest way is to use slicing. list_of_numbers = [1,0,4,2,-4,0,0,3,0,-1,0] last_5_numbers = list_of_numbers[-5:] print(last_5_numbers) #Output: [0, 3, 0, -1, 0] You can also use the islice() function from the Python itertools module in combination with the reversed() function. from itertools import islice list_of_numbers = […]
Remove Empty Strings from List in Python
To remove empty strings from a list using Python, the easiest way is to use list comprehension. list_of_strings = ["This","","is","a","list","","with","empty","","strings","."] list_without_empty_strings = [x for x in list_of_strings if x != ""] print(list_without_empty_strings) #Output: ['This', 'is', 'a', 'list', 'with', 'empty', 'strings', '.'] You can also use the Python filter() function. list_of_strings = ["This","","is","a","list","","with","empty","","strings","."] list_without_empty_strings = list(filter(lambda […]
Python Check if Attribute Exists in Object with hasattr() Function
Using Python, the easiest way to check if an attribute exists in an object is to use the Python hasattr() function. if hasattr(obj, "lower"): print("Object has attribute lower!") else: print("Object doesn't have attribute lower!") We can also use exception handling to see if an attribute exists in an object in Python. try: obj.lower() print("Object has […]
Python Check if List Index Exists Using Python len() Function
To check if a list index exists in a list using Python, the easiest way is to use the Python len() function. def indexExists(list,index): if 0 <= index < len(list): return True else: return False print(indexExists([0,1,2,3,4,5],3)) print(indexExists(["This","is","a","list"],10)) #Output: True False You can also check if an index exists using exception handling. def indexExists(list,index): try: list[index] […]
Python Check if Object is Iterable with hasattr() Function
Using Python, the easiest way to check if an object is iterable is to use the Python hasattr() function to check if the object has the “__iter__” attribute. if hasattr(obj, "__iter__"): print("Object is iterable!") else: print("Object is not iterable!") You can also use the collections module in Python to see if the variable is an […]
Find Last Occurrence in String of Character or Substring in Python
In Python, to find the last occurrence in a string of a character or substring, the easiest way is to use the Python string rfind() function. string_variable = "This is a string variable we will search." pos_of_last_a = string_variable.rfind("a") pos_of_last_w = string_variable.rfind("w") print(pos_of_last_a) print(pos_of_last_w) #Output: 36 29 You can also use the Python string rindex() […]
Find First Occurrence in String of Character or Substring in Python
In Python, to find the first occurrence in a string of a character or substring, the easiest way is to use the Python string find() function. string_variable = "This is a string variable we will search." pos_of_first_a = string_variable.find("a") pos_of_first_w = string_variable.find("w") print(pos_of_first_a) print(pos_of_first_w) #Output: 8 26 You can also use the Python string index() […]
Pythagorean Theorem in Python – Calculating Length of Triangle Sides
In Python, we can calculate the lengths of the sides of a triangle easily using the Pythagorean Theorem. def pythagoreanTheorem(toSolve,side1,side2): if toSolve == "Hypot": length = (side1 ** 2 + side2 ** 2) ** (1/2) else: if side2 < side1: temp = side2 side2 = side1 side1 = temp length = (side2 ** 2 – […]
Python Random Boolean – How to Generate Random Boolean Values
In Python, we can easily get a random boolean using the Python random() or choice() function from the random module. import random import choice, random #Using random.random() random_bool_with_random = True if random() > 0.5 else False #Using random.choice() random_bool_with_choice = choice([True, False]) print(random_bool_with_random) print(random_bool_with_choice) #Output: True False Being able to generate random numbers efficiently when […]
Python Coin Flip – How to Simulate Flipping a Coin in Python
In Python, we can simulate a coin flip and get a random result using the Python random() or choice() function from the random module. import random import choice, random #Using random.choice() coin_flip_with_choice = choice(["Heads","Tails"]) #Using random.random() coin_flip_with_random = "Heads" if random() > 0.5 else "Tails" print(coin_flip_with_choice) print(coin_flip_with_random) #Output: Tails Heads Being able to generate random […]
How to Use Python to Remove Zeros from List
To remove zeros from a list using Python, the easiest way is to use list comprehension. list_of_numbers = [1,0,4,2,-4,0,0,3,0,-1,0] list_without_zeros = [x for x in list_of_numbers if x != 0] print(list_without_zeros) #Output: [1,4,2,-4,3,-1] You can also use the Python filter() function. list_of_numbers = [1,0,4,2,-4,0,0,3,0,-1,0] list_without_zeros = list(filter(lambda x: x != 0, list_of_numbers)) print(list_without_zeros) #Output: [1,4,2,-4,3,-1] […]
How to Check if Character is Uppercase in Python
In Python, we can check if a character is uppercase by checking if the letter is equal to the letter after applying the Python upper() function. def checkCharUpper(x): return x == x.upper() print(checkCharUpper("a")) print(checkCharUpper("A")) #Output: False True When processing strings in a program, it can be useful to know which letters are uppercase and which […]
Python Round to Nearest 10 With round() Function
In Python, we can round to the nearest 10 easily with the help of the Python round() function. The Python round() function rounds to the nearest whole number, but we can make an adjustment by dividing the input to our function by 10, and then multiplying by 10. def round_to_nearest_10(x): return round(x/10)*10 print(round_to_nearest_10(14)) print(round_to_nearest_10(28)) #Output: […]
How to Find the Longest String in List in Python
With Python, we can easily find the longest string in a list of strings. To find the longest string, we loop over each element, get the length of that element, and compare to the other strings to see if it is longer. l = ["This","is","a","list","of","some","short","and","some","longer","strings"] def getLongestString(list_of_strings): longest_string = "" for string in list_of_strings: if […]
Python Get Number of Cores Using os cpu_count() Function
The easiest way to get the number of cores in Python is to use the cpu_count() function from the Python os module. import os print(os.cpu_count()) #Output: 4 The Python os module gives us many useful functions for interacting with a computer’s operating system to gather information and make changes. One piece of information which can […]
How to Check if Tuple is Empty in Python
We can easily check if a tuple is empty in Python. An empty tuple has length 0, and is equal to False, so to check if a tuple is empty, we can just check one of these conditions. empty_tuple = () #length check if len(empty_tuple) == 0: print("Tuple is empty!") #if statement check if empty_tuple: […]
How to Check if List is Empty in Python
We can easily check if a list is empty in Python. An empty list has length 0, and is equal to False, so to check if a list is empty, we can just check one of these conditions. empty_list = [] #length check if len(empty_list) == 0: print("List is empty!") #if statement check if empty_list: […]
How to Check if Set is Empty in Python
We can easily check if a set is empty in Python. An empty set has length 0, and is equal to False, so to check if a set is empty, we can just check one of these conditions. empty_set = set() #length check if len(empty_set) == 0: print("Set is empty!") #if statement check if empty_set: […]
How to Check if a Dictionary is Empty in Python
We can easily check if a dictionary is empty in Python. An empty dictionary has length 0, and is equal to False, so to check if a dictionary is empty, we can just check one of these conditions. empty_dict = {} #length check if len(empty_dict) == 0: print("Dictionary is empty!") #if statement check if empty_dict: […]
Writing Multiple Lines Lambda Expression in Python
In Python, lambda functions are typically one line functions. It is possible to write multiple line lambda functions with “\” after each line, however is not truly pythonic. lambda_expression = lambda x: True if x > 0 \ else False If you need more than 1 line for a function, it is better to define […]
Python Add Months to Datetime Variable Using relativedelta() Function
To add months to a datetime variable using Python, the easiest way is to use the Python relativedelta() function from the dateutil module. from datetime import datetime from dateutil.relativedelta import relativedelta now = datetime.now() two_months_in_future = now + relativedelta(months=2) print(now) print(two_months_in_future) #Output: 2022-02-09 08:58:25.940729 2022-04-09 08:58:25.940729 When working with data in Python, many times we […]
Add Seconds to Datetime Variable Using Python timedelta() Function
To add seconds to a datetime using Python, the easiest way is to use the Python timedelta() function from the datetime module. from datetime import timedelta, datetime now = datetime.now() one_second_in_future = now + timedelta(seconds=1) sixty_seconds_in_future = now + timedelta(seconds=60) one_hour_in_future = now + timedelta(seconds=3600) print(now) print(one_second_in_future) print(sixty_seconds_in_future) print(one_hour_in_future) #Output: 2022-02-09 15:45:53.655282 2022-02-09 15:45:54.655282 2022-02-09 […]
Python Get Yesterday’s Date
To get yesterday’s date in Python, the easiest way is to use the Python timedelta() function from the datetime module. from datetime import timedelta, date yesterday_date = date.today() – timedelta(days=1) print(date.today()) print(yesterday_date) #Output: 2022-02-08 2022-02-07 When working with data in Python, many times we are working with dates. Being able to manipulate and change dates […]
Python Subtract Days from Date Using datetime timedelta() Function
To subtract days from a datetime variable using Python, the easiest way is to use the Python timedelta() function from the datetime module. from datetime import timedelta, datetime now = datetime.now() two_days_in_past = now – timedelta(days=2) print(now) print(two_days_in_past) #Output: 2022-02-08 09:27:25.929000 2022-02-06 09:27:25.929000 When working with data in Python, many times we are working with […]
Python Add Days to Date Using datetime timedelta() Function
To add days to date using Python, the easiest way is to use the Python timedelta() function from the datetime module. from datetime import timedelta, date two_days_in_future = date.today() + timedelta(days=2) print(date.today()) print(two_days_in_future) #Output: 2022-02-08 2022-02-10 When working with data in Python, many times we are working with dates. Being able to manipulate and change […]
How to Check if a String Contains Vowels in Python
In Python, we can easily check if a string contains vowels using a for loop and check individually if each character is a vowel or not. def containsVowels(string): string = string.lower() for char in string: if char in "aeiou": return True return False print(containsVowels("Hello World!")) #Output: True When working with strings, it can be useful […]
How to Count Vowels in a String Using Python
In Python, we can easily count how many vowels are in a string using a loop and counting the number of vowels we find in the string. def countVowels(string): count = 0 string = string.lower() for char in string: if char in "aeiou": count = count + 1 return count print(countVowels("Hello World!")) #Output: 3 When […]
Python Indicator Function – Apply Indicator Function to List of Numbers
In Python, we can define and apply indicator functions easily. To apply an indicator function to a list of numbers using Python, the easier way is with list comprehension. list_of_nums = [10,-4,2,0,-8] indicator = [1 if x > 0 else 0 for x in list_of_nums] print(indicator) #Output: [1, 0, 1, 0, 0] An indicator function […]
Count Primes Python – How to Count Number of Primes in a List
In Python, we can count the number of primes in a list by defining a function to check if a number is prime, and then looping through the list and adding up the count. def isPrime(n): if (n % 2 == 0): return False for i in range(3, int(n**0.5 + 1), 2): if (n % […]
How to Check if Number is Power of 2 in Python
In Python, we can easily check if a number is a power of 2 by taking the log base 2 and seeing if the result is a whole number. import math def isPowerOfTwo(num): if math.log(num,2).is_integer(): return True else: return False print(isPowerOfTwo(2)) print(isPowerOfTwo(12)) print(isPowerOfTwo(32)) print(isPowerOfTwo(94)) #Output: True False True False When working with numbers in our […]
Python Logging Timestamp – Print Current Time to Console
In Python, it can be very useful to add a timestamp when logging information to the console. We can log the timestamp to the console with the logging module easily by adjusting the basic configuration. import logging logging.basicConfig( format='%(asctime)s %(levelname)-8s %(message)s', level=logging.INFO, datefmt='%Y-%m-%d %H:%M:%S') logging.info('Message for the user.') #Output: 2022-01-25 07:58:28 INFO Message for the […]
How to Get the Size of a List in Python Using len() Function
To find the size of a list in Python, the easiest way is to use the Python len() function. The len() function returns the length of the list and the number of elements in the list. length_of_list = len(list_variable) In Python, lists are a collection of objects which are unordered and mutable. When working with […]
How to Declare Variable Without Value in Python
In Python, sometimes it makes sense to declare a variable and not assign a value. To declare a variable without a value in Python, use the value “None”. variable_without_value = None You can also use what Python calls “type hints” to declare a variable without a value. variable_without_value: str #variable with type string with no […]
How to Check if Number is Divisible by 3 in Python
In Python, we can check if a number is divisible by 3 very easily with the Python built in remainder operator %. If the remainder of a number after dividing by 3 is 0, then the number is divisible by 3. def isDivisibleBy3(num): if (num % 3) == 0: return True else: return False print(isDivisibleBy3(10)) […]
Python Even or Odd – Check if Number is Even or Odd Using % Operator
In Python, we can check if a number is even or odd very easily with the Python built in remainder operator %. If the remainder of a number after dividing by 2 is 0, then the number is even. If not, the number is odd. def isEven(num): if (num % 2) == 0: return True […]
islower Python – Check if All Letters in String Are Lowercase
To check if all characters in a string are lowercase, we can use the Python built-in string islower() function. string_1 = "This is a String with SOME letters." string_2 = "hello" print(islower(string_1)) print(islower(string_2)) #Output: False True When working with strings in Python, being able to get information about your variables easily is important. There are […]
Python Replace Space With Dash Using String replace() Function
To replace a space with a dash in Python, the easiest way is to use the Python built-in string replace() function. string_with_spaces = "This is a string." string_with_dashes = string_with_spaces.replace(" ","-") print(string_with_dashes) #Output: This-is-a-string. When working with strings in Python, being able to manipulate your variables easily is important. There are a number of built […]
Python Replace Space with Underscore Using String replace() Function
To replace a space with an underscore in Python, the easiest way is to use the Python built-in string replace() function. string_with_spaces = "This is a string." string_with_underscores = string_with_spaces.replace(" ","_") print(string_with_underscores) #Output: This_is_a_string. When working with strings in Python, being able to manipulate your variables easily is important. There are a number of built […]
Python isprime – Function for Determining if Number is Prime
Finding out if a number is prime is easy to do in Python. We can determine if a number is prime if it has no factors between 2 and the square root of the number. Below is a function which will determine if a number is prime in Python. def isPrime(n): if (n <= 1): […]
Python Prime Factorization – Find Prime Factors of Number
Prime factorization is easy to do in Python. We can find the prime factors of a number by defining a function, applying some logic to get the prime factors, and returning a list of the prime factors. Below is a function which will get the prime factorization of a number in Python. def prime_factorization(n): prime_factors […]
Python max() function – Get Maximum of List or Dictionary with max() Function
To get the maximum of a list of numbers or strings in Python, we can use the Python max() function. You can use the max() function in Python to get the maximum value of numbers in a list, strings in a list, and values in a dictionary. list_of_numbers = [10,32,98,38,47,34] print(max(list_of_numbers)) #Output 98 There are […]
Python min() function – Get Minimum of List or Dictionary with min() Function
To get the minimum of a list of numbers or strings in Python, we can use the Python min() function. You can use the min() function in Python to get the minimum value of numbers in a list, strings in a list, and values in a dictionary. list_of_numbers = [10,32,98,38,47,34] print(min(list_of_numbers)) #Output 10 There are […]
Ceiling Function Python – Get Ceiling of Number with math.ceil()
To find the ceiling of a number in Python, we can use the Python ceil() function from the math module. The math.ceil() Python function rounds a number up to the nearest integer. import math ceiling_of_5p2 = math.ceil(5.2) print(ceiling_of_5p2) #Output: 6 The Python math module has many powerful functions which make performing certain calculations in Python […]
Floor in Python – Find Floor of Number with math.floor() Function
To find the floor of a number in Python, we can use the Python floor() function from the math module. The math.floor() Python function rounds a number down to the nearest integer. import math floor_of_5p2 = math.floor(5.2) print(floor_of_5p2) #Output: 5 The Python math module has many powerful functions which make performing certain calculations in Python […]
Python Trig – Using Trigonometric Functions in Python for Trigonometry
In Python, we can easily do trigonometry with the many trig functions from the Python math module. In this article, you will learn about all the trigonometric functions that you can use in Python to perform trigonometry easily. In Python, we can easily use trigonometric functions with the Python math module. The Python math module […]
math.degrees() Python – How to Convert Radians to Degrees in Python
To convert radians to degrees for use in trigonometric functions in Python, the easiest way is with the math.degrees() function from the Python math module. import math degrees = math.degrees(math.pi/2) The Python math module has many powerful functions which make performing certain calculations in Python very easy. One such calculation which is very easy to […]
math.radians() python – How to Convert Degrees to Radians in Python
To convert degrees to radians for use in trigonometric functions in Python, the easiest way is with the math.radians() function from the Python math module. import math radians = math.radians(60) The Python math module has many powerful functions which make performing certain calculations in Python very easy. One such calculation which is very easy to […]
Length of Set Python – Get Set Length with Python len() Function
To find the length of a set in Python, the easiest way is to use the Python len() function. The len() function returns the number of elements in the set and the size of the set. length_of_set = len(set) In Python, sets are a collection of elements which is unordered and mutable. When working with […]
Python max float – What’s the Maximum Float Value in Python?
The maximum float value in Python is 1.7976931348623157e+308. To find the max float in Pythoon, we can use the sys module and access the float_info property. import sys print(sys.float_info) #Output: sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1) When working with numbers in any programming language, knowing the min and max values […]
Python if else do nothing – Using pass Statement to Do Nothing in Python
To tell Python to do nothing, we can use the pass statement. For example, in an if-else block, if a condition holds, we can tell Python to move on to the next block of code. if x == 2: pass #pass tells Python to do nothing In Python, the pass statement is very useful for […]
Length of Dictionary Python – Get Dictionary Length with len() Function
To find the length of a dictionary in Python, the easiest way is to use the Python len() function. The len() function returns the number of key/value pairs in the dictionary and the size of the dictionary. length_of_dictionary = len(dictionary) In Python, dictionaries are a collection of key/value pairs separated by commas. When working with […]
Length of Tuple Python – Find Tuple Length with Python len() Function
To find the length of a tuple in Python, the easiest way is to use the Python len() function. The len() function returns the number of elements in the tuple. length_of_tuple = len(tuple) In Python, tuples are a collection of objects which are ordered and mutable. When working with tuples, it can be useful to […]
Factorial Program in Python Using For Loop and While Loop
Using Python, we can calculate factorials using loops. Defining a iterative function to find the factorial of a nonnegative integer in Python can be done in the following code. Below is a function which uses a for loop to find the factorial of a number. def factorial_with_for_loop(n): if isinstance(n,int) and n >= 0: if n […]
Python Factorial Recursion – Using Recursive Function to Find Factorials
Using Python, we can calculate factorials using recursion. Defining a recursive function to find the factorial of a nonnegative integer in Python can be done in the following code. def factorial_with_recursion(n): if isinstance(n,int) and n >= 0: if n == 0 or n == 1: return 1 else: return n * factorial_with_recursion(n-1) else: return "Not […]
Python math.factorial() function – Calculate Factorial of Number
In Python, the easiest way to find the factorial of an nonnegative integer number is with the Python factorial() function from the math module. import math factorial_of_5 = math.factorial(5) The Python math module has many powerful functions which make performing certain calculations in Python very easy. One such calculation which is very easy to perform […]
Log Base 10 Python – Find Logarithm of Number with Base 10 with log10()
In Python, to calculate the logarithm of a number with base 10, we can use the Python log10() function from the Python math module. log_base_10 = log10(x) You can also use the log() function from the Python math module, but this will be slightly less accurate. log_base_10 = log(x,10) The Python math module has many […]
Python power function – Exponentiate Numbers with math.pow()
The Python power function pow() from the math module allows us to perform exponentiation and find roots of numbers easily. import math square_of_4 = math.pow(4,2) sqrt_of_4 = math.pow(4,1/2) The Python math module has many powerful functions which make performing certain calculations in Python very easy. One such calculation which is very easy to perform in […]
Squaring in Python – Square a Number Using Python math.pow() Function
To square a number in Python, the easiest way is to multiply the number by itself. square_of_10 = 10*10 We can also use the pow() function from the math module to square a number. import math square_of_10 = math.pow(10,2) Finally, we can find the square of a number in Python with the built in exponentiation […]
Python Square Root Without Math Module – ** or Newton’s Method
In Python, the easiest way to find the square root of a number without the math module is with the built in exponentiation operator **. sqrt_of_10 = 10**(1/2) When working with numeric data in Python, one calculation which is valuable is finding the square root of a number. We can find the square root of […]
Python nth Root – Find nth Root of Number with math.pow() Function
In Python, the easiest way we can find the nth root of a number is to use the pow() function from the Python math module. import math n = 3 cube_root_of_10 = math.pow(10,1/n) #nth root of 10 where n = 3 You can also use the built in ** operator to find the nth root […]
Python cube root – Find Cube Root of Number With math.pow() Function
In Python, the easiest way we can find the cube root of a number is to use the pow() function from the Python math module. import math cube_root_of_10 = math.pow(10,1/3) You can also use the built in ** operator to find the cube root of a number. cube_root_of_10 = 10**(1/3) The Python math module has […]
Python Square Root – Finding Square Roots Using math.sqrt() Function
In Python, the easiest way we can find the square root of a positive number is to use the sqrt() function from the Python math module. import math sqrt_of_10 = math.sqrt(10) If you want to find the square root of a negative number, you should use the Python cmath module. This will return an imaginary […]
pi in Python – Using Math Module and Leibniz Formula to Get Value of pi
To get the value of pi in Python, the easiest way is use the Python math module constant pi. math.pi returns the value 3.141592653589793. import math print(math.pi) #Output: 3.141592653589793 You can also use the numpy module to get the value of pi. import numpy as np print(np.pi) #Output: 3.141592653589793 In Python, we can easily get […]
Python atanh – Find Hyperbolic Arctangent of Number Using math.atanh()
To find the hyperbolic arctangent of a number, we can use the Python atanh() function from the math module. import math math.atanh(x) In Python, we can easily use trigonometric functions with the Python math module. The Python math module allows us to perform trigonometry easily and in addition to regular trigonometry, we have access to […]
Python tanh – Find Hyperbolic Tangent of Number Using math.tanh()
To find the hyperbolic tangent of a number, we can use the Python tanh() function from the math module. import math math.tanh(x) In Python, we can easily use trigonometric functions with the Python math module. The Python math module allows us to perform trigonometry easily and in addition to regular trigonometry, we have access to […]
Python acosh – Find Hyperbolic Arccosine of Number Using math.acosh()
To find the hyperbolic arccosine of a number, we can use the Python acosh() function from the math module. import math math.acosh(x) In Python, we can easily use trigonometric functions with the Python math module. The Python math module allows us to perform trigonometry easily and in addition to regular trigonometry, we have access to […]
Python asinh – Find Hyperbolic Arcsine of Number Using math.asinh()
To find the hyperbolic arcsine of a number, we can use the Python asinh() function from the math module. import math math.asinh(x) In Python, we can easily use trigonometric functions with the Python math module. The Python math module allows us to perform trigonometry easily and in addition to regular trigonometry, we have access to […]
Python cosh – Find Hyperbolic Cosine of Number Using math.cosh()
To find the hyperbolic cosine of a number, we can use the Python cosh() function from the math module. import math math.cosh(x) In Python, we can easily use trigonometric functions with the Python math module. The Python math module allows us to perform trigonometry easily and in addition to regular trigonometry, we have access to […]
Python sinh – Find Hyperbolic Sine of Number Using math.sinh()
To find the hyperbolic sine of a number, we can use the Python sinh() function from the math module. import math math.sinh(x) In Python, we can easily use trigonometric functions with the Python math module. The Python math module allows us to perform trigonometry easily and in addition to regular trigonometry, we have access to […]
Python atan2 – Find Arctangent of the Quotient of Two Numbers
To find the arctangent, or inverse tangent, of the quotient of two numbers, we can use the Python atan2() function from the math module. import math math.atan2(x,y) In Python, we can easily use trigonometric functions with the Python math module. The Python math module allows us to perform trigonometry easily. With the Python math module, […]
Python atan – Find Arctangent and Inverse Tangent of Number
To find the arctangent, or inverse tangent, of a number, we can use the Python atan() function from the math module. import math math.atan(x) In Python, we can easily use trigonometric functions with the Python math module. The Python math module allows us to perform trigonometry easily. With the Python math module, we can find […]
Python acos – Find Arccosine and Inverse Cosine of Number
To find the arccosine, or inverse cosine, of a number, we can use the Python acos() function from the math module. import math math.acos(x) In Python, we can easily use trigonometric functions with the Python math module. The Python math module allows us to perform trigonometry easily. With the Python math module, we can find […]
Python asin – Find Arcsine and Inverse Sine of Number Using math.asin()
To find the arcsine, or inverse sine, of a number, we can use the Python asin() function from the math module. import math math.asin(x) In Python, we can easily use trigonometric functions with the Python math module. The Python math module allows us to perform trigonometry easily. With the Python math module, we can find […]
Python cos – Find Cosine of Number in Radians Using math.cos()
To find the cosine of a number (in radians), we can use the Python cos() function from the math module. import math math.cos(x) In Python, we can easily use trigonometric functions with the Python math module. The Python math module allows us to perform trigonometry easily. With the Python math module, we can find the […]
Python tan – Find Tangent of Number in Radians Using math.tan()
To find the tangent of a number (in radians), we can use the Python tan() function from the math module. import math math.tan(x) In Python, we can easily use trigonometric functions with the Python math module. The Python math module allows us to perform trigonometry easily. With the Python math module, we can find the […]
Python sin – Find Sine of Number in Radians Using math.sin()
To find the sine of a number (in radians), we can use the Python sin() function from the math module. import math math.sin(x) In Python, we can easily use trigonometric functions with the Python math module. The Python math module allows us to perform trigonometry easily. With the Python math module, we can find the […]
pandas ewm – Calculate Exponentially Weighted Statistics in DataFrame
To calculate exponential moving averages in pandas, we can use the pandas ewm() function. df.ewm(span=10, adjust=False).mean() # Calculate the Exponential Weighted Moving Average over a span of 10 periods When working with data, many times we want to calculate summary statistics to understand our data better. One such statistic is the moving average of time […]
pandas groupby size – Get Number of Elements after Grouping DataFrame
To get the total number of elements in a pandas DataFrame after grouping, we can use the pandas DataFrame groupby size() function . grouped_data = df.groupby(["Column1"]) grouped_data.size() # Returns number of elements in each group in the grouped DataFrame When working with data, it is useful for us to be able to find the number […]
pandas DataFrame size – Get Number of Elements in DataFrame or Series
To get the total number of elements in a pandas DataFrame, we can use the pandas DataFrame size property. df.size # Returns number of rows times number of columns You can also find the number of elements in a DataFrame column or Series using the pandas size property. df["Column"].size # Returns number of rows When […]
pandas head – Return First n Rows from DataFrame
To get the first n rows from a pandas DataFrame, you can use the pandas head() function. df.head() #Default will return the first 5 rows When working with data and designing scripts to update data, sometimes it is useful to be able to do simple checks on our data to ensure everything is populating correctly. […]
pandas tail – Return Last n Rows from DataFrame
To get the last n rows from a pandas DataFrame, you can use the pandas tail() function. df.tail() #Default will return the last 5 rows When working with data and designing scripts to update data, sometimes it is useful to be able to do simple checks on our data to ensure everything is populating correctly. […]
pandas set_value – Using at() Function to Set a Value in DataFrame
To set a value in a pandas DataFrame, the easiest way is to use the pandas at() function. df.at[row,column] = value The pandas set_value() method was deprecated in version 0.21. When working with data, the ability to update fields on the fly can be very useful. We can use the pandas at() function to set […]
pandas cumprod – Find Cumulative Product of Series or DataFrame
To calculate the cumulative product over columns in a DataFrame, or the cumulative product of the values of a Series in pandas, the easiest way is to use the pandas cumsum() function. df.cumprod() # Calculate cumulative product for all columns df["Column"].cumprod() #calculate cumulative productfor 1 column You can also use the numpy cumprod() function to […]
pandas product – Get Product of Series or DataFrame Columns
To find the product of the values in columns in a DataFrame, or the product of the values of a Series in pandas, the easiest way is to use the pandas prod() function. df.prod() # Calculate products for all columns df["Column"].prod() #calculate product for 1 column The pandas product() function is equivalent to the pandas […]
pandas cumsum – Find Cumulative Sum of Series or DataFrame
To calculate the cumulative sum over columns in a DataFrame, or the cumulative sum of the values of a Series in pandas, the easiest way is to use the pandas cumsum() function. df.cumsum() # Calculate cumulative sum for all columns df["Column"].cumsum() #calculate cumulative sum for 1 column You can also use the numpy cumsum() function […]
pandas sum – Get Sum of Series or DataFrame Columns
To find the sum of columns in a DataFrame, or the sum of the values of a Series in pandas, the easiest way is to use the pandas sum() function. df.sum() # Calculate sum for all columns df["Column"].sum() #calculate sum for 1 column You can also use the numpy sum() function. np.sum(df["Column"]) #calculate sum for […]
pandas Drop Rows – Delete Rows from DataFrame with drop()
To drop rows from a pandas DataFrame, the easiest way is to use the pandas drop() function. df.drop(1) #drop the row with index 1 When working with data, it can be useful to add or delete elements from your dataset easily. By deleting elements from your data, you are able to focus more on the […]
pandas Drop Columns – Delete Columns from a DataFrame
To drop a column from a pandas DataFrame, the easiest way is to use the pandas drop() function. df.drop(columns=["Column1"]) #drop "Column1" using columns parameter df.drop(["Column1"],axis=1) #drop "Column1" using axis parameter When working with data, it can be useful to add or delete elements from your dataset easily. By deleting columns from your data, you are […]
pandas drop – Drop Rows or Columns from DataFrame
To drop rows, or columns, from a pandas DataFrame, the easiest way is to use the pandas drop() function. df.drop(1) #drop the row with index 1 When working with data, it can be useful to add or delete elements from your dataset easily. By deleting elements from your data, you are able to focus more […]
pandas dropna – Drop Rows or Columns with NaN in DataFrame
To drop rows or columns with missing values in a DataFrame and using pandas, the simplest way is to use the pandas dropna() function. df = df.dropna() #drops rows with missing values df["Column 1"] = df["Column 1"].dropna() #drops rows with missing values in column "Column 1" df = df.dropna(axis=1) #drop columns with missing values When […]
Drop Duplicates pandas – Remove Duplicate Rows in DataFrame
To drop duplicate rows in a DataFrame or Series in pandas, the easiest way is to use the pandas drop_duplicates() function. df.drop_duplicates() When working with data, it’s important to be able to find any problems with our data. Finding and removing duplicate records in our data is one such situation where we may have to […]
pandas Duplicated – Find Duplicate Rows in DataFrame or Series
To find duplicate rows in a DataFrame or Series in pandas, the easiest way is to use the pandas duplicated() function. df.duplicated() When working with data, it’s important to be able to find any problems with our data. Finding duplicate records in our data is one such situation where we may need to take additional […]
pandas variance – Compute Variance of Variables in DataFrame
To find the variance of a series or a column in a DataFrame in pandas, the easiest way is to use the pandas var() function. df["Column1"].var() You can also use the numpy var() function, but be careful as the default algorithm is different than the default pandas var() algorithm. np.var(df["Column1"]) #Different result from default pandas […]
pandas mad – Calculate Mean Absolute Deviation in Python
To find the mean absolute deviation of a series or a column in a DataFrame in pandas, the easiest way is to use the pandas mad() function. df["Column1"].mad() When doing data analysis, the ability to compute different summary statistics, such as the mean or standard deviation of a variable, is very useful to help us […]
Using Matplotlib and Seaborn to Create Pie Chart in Python
Using Matplotlib and Seaborn, you can create a pie chart in your Python code. Seaborn is a fantastic statistical data visualization package, but does not give us the ability to create a pie chart. However, we can create a pie chart using Matplotlib and add a Seaborn color palette. We can create a “Seaborn” Pie […]
pandas mean – Get Average of Series or DataFrame Columns
To find the means of the columns in a DataFrame, or the average value of a Series in pandas, the easiest way is to use the pandas mean() function. df.mean() You can also use the numpy mean() function. np.mean(df["Column"]) When working with data, many times we want to calculate summary statistics to understand our data […]
pandas covariance – Calculate Covariance Matrix Using cov() Function
To find the covariance between columns in a DataFrame or Series in pandas, the easiest way is to use the pandas cov() function. df.cov() You can also use the numpy cov() function to calculate the covariance between two Series. s1.cov(s2) Finding the covariance between columns or Series using pandas is easy. We can use the […]
pandas Standard Deviation – Using std() to Find Standard Deviation
To find the standard deviation of a series or a column in a DataFrame in pandas, the easiest way is to use the pandas std() function. df["Column1"].std() You can also use the numpy std() function, but be careful as the default algorithm is different than the default pandas std() algorithm. np.std(df["Column1"]) #Different result from default […]
pandas percentile – Calculate Percentiles of Series or Columns in DataFrame
To find percentiles of a numeric column in a DataFrame, or the percentiles of a Series in pandas, the easiest way is to use the pandas quantile() function. df.quantile(0.25) You can also use the numpy percentile() function. np.percentile(df["Column"], 25) When working with data, many times we want to calculate summary statistics to understand our data […]
pandas mode – Find Mode of Series or Columns in DataFrame
To find the modes of the columns in a DataFrame, or the mode value of a Series in pandas, the easiest way is to use the pandas mode() function. df.mode() When working with data, many times we want to calculate summary statistics to understand our data better. One such statistic is the mode, or the […]
pandas median – Find Median of Series or Columns in DataFrame
To find the medians of the columns in a DataFrame, or the median value of a Series in pandas, the easiest way is to use the pandas median() function. df.median() You can also use the numpy median() function. np.median(df["Column"]) When working with data, many times we want to calculate summary statistics to understand our data […]
pandas Correlation – Find Correlation of Series or DataFrame Columns
To find the correlation between series or columns in a DataFrame in pandas, the easiest way is to use the pandas corr() function. df["Column1"].corr(df["Column2"]) If you want to compute the pairwise correlations between all numeric columns in a DataFrame, you can call corr() directly on the DataFrame. df.corr() You can also use the pandas corrwith() […]
pandas nsmallest – Find Smallest Values in Series or Dataframe
To find the smallest values in a Series or Dataframe column using pandas, the easiest way is to use the pandas nsmallest() function. df.nsmallest(n,"column") By default, The pandas nsmallest() function returns the first n smallest rows in the given columns in ascending order. Finding the smallest values of a column or Series using pandas is […]
pandas nlargest – Find Largest Values in Series or Dataframe
To find the largest values in a Series or Dataframe column using pandas, the easiest way is to use the pandas nlargest() function. df.nlargest(n,"column") By default, The pandas nlargest() function returns the first n largest rows in the given columns in descending order. Finding the largest values of a column or Series using pandas is […]
pandas unique – Get Unique Values in Column of DataFrame
To get the unique values of a column in pandas, the simplest way is to use the pandas unique() function. df["variable"].unique() You can also use the pandas unique() function in the following way: pd.unique(series) When working with data as a data science or data analyst, it’s sometimes important to be able to easily find the […]
pandas str replace – Replace Text in Dataframe with Regex Patterns
In pandas, we can use the str.replace() function to replace text in a Series or column in a Dataframe. The str.replace() function allows us to perform a string search or regular expression (regex) search on the elements in a Series or column and replace them. series.str.replace(r'/\s\s+/','new_text',regex=True) From the pandas documentation, the pandas str.replace() function takes […]
Transpose DataFrame pandas – Using the pandas transpose Function
The pandas transpose function allows us to transpose a dataframe. Transposing a dataframe reflects the rows into columns and columns into rows over the main diagonal. transposed_df = df.transpose() We can also use the pandas T function to transpose a dataframe. transposed_df = df.T When working with data as a data science or data analyst, […]
pandas T Function – Transposing DataFrames with pandas
The pandas T function allows us to transpose a dataframe. Transposing a dataframe reflects the rows into columns and columns into rows over the main diagonal. The pandas T function is the same as the pandas transpose() function. transposed_df = df.T When working with data as a data science or data analyst, manipulating the structure […]
Read Pickle Files with pandas read_pickle Function
To read a pickle file and create a DataFrame in Python, the simplest way is to use the pandas read_pickle() function. df.read_pickle("./filename.pkl") When working with data as a data science or data analyst, many times we want to read data and write data to different file types. One common file type which analysts use is […]
pandas to_pickle – Write DataFrame to Pickle File
To write a DataFrame to a pickle file, the simplest way is to use the pandas to_pickle() function. df.to_pickle("./filename.pkl") When working with data as a data science or data analyst, many times we want to read data and write data to different file types. One common file type which analysts use is a pickle file. […]
nunique pandas – Get Number of Unique Values in DataFrame
To get the number of unique values in a pandas DataFrame or Series, the simplest way is to use the pandas nunique() function. df["variable"].nunique() When working with data, it’s important to be able to find the basic descriptive statistics of a set of data. One basic descriptive statistic which is important is the number of […]
pandas round – Round Numbers in Series or DataFrame
To round numbers in a column or DataFrame using pandas, the easiest way is to use the pandas round() function. df["Column"] = df["Column"].round() If you want to round to a specific number of decimal places, you can pass the number of decimal places to the round() function. df["Column"] = df["Column"].round(1) Rounding numbers in a column […]
pandas idxmax – Find Index of Maximum Value of Series or DataFrame
To find the index of the maximum value of a column in pandas, the easiest way is to use the pandas idxmax() function. df["Column"].idxmax() If you are working with a Series object, you can also use idxmax() function. series.idxmax() Finding the index of the maximum value of numbers in a column in a DataFrame using […]
pandas idxmin – Find Index of Minimum Value of Series or DataFrame
To find the index of the minimum value of a column in pandas, the easiest way is to use the pandas idxmin() function. df["Column"].idxmin() If you are working with a Series object, you can also use idxmin() function. series.idxmin() Finding the index of the minimum value of numbers in a column in a DataFrame using […]
pandas max – Find Maximum Value of Series or DataFrame
To find the maximum value of a column in pandas, the easiest way is to use the pandas max() function. df["Column"].max() You can also use the numpy max() function. np.max(df["Column"]) Finding the maximum value of numbers in a column, or the maximum value of all numbers in a DataFrame using pandas is easy. We can […]
pandas min – Find Minimum Value of Series or DataFrame
To find the minimum value of a column in pandas, the easiest way is to use the pandas min() function. df["Column"].min() You can also use the numpy min() function. np.min(df["Column"]) Finding the minimum value of numbers in a column, or the minimum value of all numbers in a DataFrame using pandas is easy. We can […]
pandas Absolute Value – Get Absolute Values in a Series or DataFrame
To find the absolute value in pandas, the easiest way is to use the pandas abs() function. df["Column"] = df["Column"].abs() You can also use the numpy abs() function and apply it to a column. df["Column"] = df["Column"].apply(np.abs) Finding the absolute value of numbers in a column, or the absolute value of all numbers in a […]
pandas ceil – Find the Ceiling of a Column Using Numpy ceil
To find the ceiling of numbers in a column using pandas, the easiest way is to use the numpy ceil() function. df["Column"] = df["Column"].apply(np.ceil) Finding the ceiling of numbers in a column in pandas is easy. We can round up numbers in a column to the nearest integer with the numpy ceil() function. Let’s say […]
pandas floor – Find the Floor of a Column Using Numpy floor
To find the floor of numbers in a column using pandas, the easiest way is to use the numpy floor() function. df["Column"] = df["Column"].apply(np.floor) Finding the floor of numbers in a column in pandas is easy. We can round down numbers in a column to the nearest integer with the numpy floor() function. Let’s say […]
Pandas Crosstab on Multiple Columns
When working with data, it is very useful to be able to group and aggregate data by multiple columns to understand the various segments of our data. With pandas, we can easily find the frequencies of columns in a dataframe using the pandas value_counts() function, and we can do cross tabulations very easily using the […]
PROC FREQ Equivalent in Python
When working with data as a data science or data analyst, calculating frequencies is very common and something that many industries and companies utilize to compare the means of two distinct populations. There are many major companies and industries which use SAS (banking, insurance, etc.), but with the rise of open source and the popularity […]
Sort a List of Strings Using Python
To sort a list of strings using Python, the simplest way is to use the Python sort() function. list_object.sort() You can also sort a list of string using the Python sorted() function. sorted_list_object = sorted(list_object) Let’s say I have the following list of strings that I want to sort in Python: l = ["this","is","a","list","of","strings"] We can sort […]
pandas fillna – Replace NaN in Dataframe using Python
To replace NaN in a dataframe, the simplest way is to use the pandas fillna() function. You can replace NaN values on a single or multiple columns, or replace NaN values for the entire dataframe with both numbers and strings. df = df.fillna(0) #replacing NaN values with 0 for the entire dataframe df["col_name"] = df["col_name"].fillna("") […]
How to Group and Aggregate By Multiple Columns in Pandas
When working with data, it is very useful to be able to group and aggregate data by multiple columns to understand the various segments of our data. Using pandas, we can easily group data using the pandas groupby function. However, when grouping by multiple columns and looking to compute summary statistics, we need to do […]
How to Iterate over Everything in Word Document using python-docx
Many times, when working with documentation, it would be helpful if we could use code to read, create and manipulate files to make processes more efficient. In many organizations, Microsoft Word files are used for reporting and different processes, and from time to time, we need to update the data stored in these files. Having […]
How to Read XLSX File from Remote Server Using Paramiko FTP and Pandas
Many times, when working with files and remote servers, it would be helpful if we could use code to manipulate directories and files to make processes more efficient. In many organizations, Microsoft Excel files store data for different processes, and from time to time, we need to update the data stored in these files. Having […]
How to Save and Use Styles from Existing Word File With python-docx
Creating Word documents using the Python Docx package is very powerful and allows us to present our data and findings in an automated way. In corporate settings, when working with Word and other Office products, usually you will have standards for branding and different templates for each document you produce. When creating Word documents using […]
Writing a Table Faster to Word Document Using python-docx
Creating Word documents using the Python Docx package is very powerful and allows us to present our data and findings in an automated way. Many times, we are working with data and want to output this data into a table. Outputting data to a table in a Word Document in Python is not difficult, but […]
Set Widths of Columns in Word Document Table with python-docx
Creating Word documents using the Python Docx package is very powerful and allows us to present our data and findings in an automated way. Many times, we are working with data and want to output this data into a table. Outputting data to a table in a Word Document in Python is not difficult, but […]
How to Output XLSX File from Pandas to Remote Server Using Paramiko FTP
Many times, when working with files and remote servers, it would be helpful if we could use code to manipulate directories and files to make processes more efficient. In many organizations, Microsoft Excel files store data for different processes, and from time to time, we need to update the data stored in these files. Having […]
PROC MIXED Equivalent in Python for Least Squared Means ANOVA
When working with data as a data science or data analyst, ANOVA is very common and something that many industries and companies utilize to compare the means of two distinct populations. There are many major companies and industries which use SAS (banking, insurance, etc.), but with the rise of open source and the popularity of […]
How to Serialize a Model Object with a List of Lists Using Django Rest Framework in Python
When creating an API using the Django REST Framework, it’s very common to have nested models. Often, we will want to serialize these nested models in a similar way to how the models are defined. But what about the case where we have nested models of nested models? If we have to serialize a model […]
PROC LIFETEST Equivalent in Python
When working with data as a data science or data analyst, survival analysis is very common and something that many industries and companies utilize to understand the expected time and probabilities of some event occurring. There are many major companies and industries which use SAS (banking, insurance, etc.), but with the rise of open source […]
PROC PHREG Equivalent in Python
When working with data as a data science or data analyst, survival analysis is very common and something that many industries and companies utilize to understand the expected time and probabilities of some event occurring. There are many major companies and industries which use SAS (banking, insurance, etc.), but with the rise of open source […]
Get the Count of NaN in pandas Using Python
To get the count of NaN in a pandas dataframe, the simplest way is to use the pandas isnull() function and pandas sum() function. df["variable"].isnull().sum() When working with data as a data science or data analyst, it’s important to be able to find the basic descriptive statistics of a set of data. One basic descriptive […]
PROC MEANS Equivalent in Python
When working with data as a data science or data analyst, it’s important to be able to find the basic descriptive statistics of a set of data. There are many major companies and industries which use SAS (banking, insurance, etc.), but with the rise of open source and the popularity of languages such as Python […]
PROC REG Equivalent in Python
When working with data as a data science or data analyst, regression analysis is very common and something that many industries and companies utilize to understand how different series of data are related. There are many major companies and industries which use SAS (banking, insurance, etc.), but with the rise of open source and the […]