Trending March 2024 # Using The Append() Method In Python # Suggested April 2024 # Top 10 Popular

You are reading the article Using The Append() Method In Python updated in March 2024 on the website We hope that the information we have shared is helpful to you. If you find the content interesting and meaningful, please share it with your friends and continue to follow and support us for the latest updates. Suggested April 2024 Using The Append() Method In Python

One of the essential features of Python is the ability to manipulate lists, which are collections of items of the same or different data types such as strings, integers, or even other lists. In this article, we will explore the append() method, which is a built-in function in Python that allows you to add an item to the end of a list.

What is Python Append?

The append() method is a list method in Python that adds an item to the end of a list. The syntax of the append() method is as follows:


Here, list is the name of the list to which you want to add an item, and item is the value that you want to append. The append() method modifies the original list and returns None. It does not create a new list.

How to Use Python Append?

Let’s look at some examples of how to use the append() method in Python.

Example 1: Adding an Integer to a List numbers = [1, 2, 3, 4] numbers.append(5) print(numbers)


[1, 2, 3, 4, 5]

In this example, we have a list of integers called numbers. We use the append() method to add the integer 5 to the end of the list. The print() function is used to display the modified list.

Example 2: Adding a String to a List fruits = ['apple', 'banana', 'cherry'] fruits.append('orange') print(fruits)


['apple', 'banana', 'cherry', 'orange']

In this example, we have a list of strings called fruits. We use the append() method to add the string ‘orange’ to the end of the list. The print() function is used to display the modified list.

Example 3: Adding a List to a List list1 = [1, 2, 3] list2 = [4, 5, 6] list1.append(list2) print(list1)


[1, 2, 3, [4, 5, 6]]

In this example, we have two lists called list1 and list2. We use the append() method to add list2 to the end of list1. As a result, list1 becomes a nested list that contains both the original elements and the new list.

Example 4: Adding Multiple Items to a List colors = ['red', 'green', 'blue'] colors.append('yellow', 'purple') print(colors)


TypeError: append() takes exactly one argument (2 given)

In this example, we have a list of strings called colors. We attempt to add two strings, ‘yellow’ and ‘purple’, to the end of the list using the append() method. However, this results in a TypeError because the append() method can only accept one argument at a time.

Example 5: Using Append in a Loop numbers = [] for i in range(1, 6): numbers.append(i) print(numbers)


[1, 2, 3, 4, 5]

In this example, we create an empty list called numbers. We use a for loop to iterate from 1 to 5 and append each integer to the end of the list. The print() function is used to display the modified list.

Related Concepts and Methods

There are several other list methods in Python that are related to the append() method and can be useful in various scenarios.


This method can be used to append all the elements of an iterable to a list. For example:

list1 = [1, 2, 3] list2 = [4, 5, 6] list1.extend(list2) print(list1)


[1, 2, 3, 4, 5, 6] insert(index, item)

This method can be used to insert an item at a specific position in a list. For example:

numbers = [1, 2, 3, 4] numbers.insert(2, 2.5) print(numbers)


[1, 2, 2.5, 3, 4] remove(item)

This method can be used to remove the first occurrence of an item from a list. For example:

colors = ['red', 'green', 'blue', 'green'] colors.remove('green') print(colors)


['red', 'blue', 'green'] pop(index)

This method can be used to remove and return the item at a specific position in a list. If no index is specified, it removes and returns the last item in the list. For example:

numbers = [1, 2, 3, 4] last_number = numbers.pop() print(last_number) print(numbers)


4 [1, 2, 3]

By understanding these related concepts and methods, you can expand your knowledge of list manipulation in Python and write more efficient and effective code.


The append() method in Python is a simple yet powerful way to add an item to the end of a list. By using this method, you can modify lists dynamically and create complex data structures that can be used in a variety of applications. Whether you are a beginner or an experienced Python programmer, understanding the append() method and its related concepts is an essential skill that can help you write better code and solve more complex problems.

You're reading Using The Append() Method In Python

Using The Format Method In Python

Python format is a method used to format strings in a more readable and user-friendly way. It allows you to insert values into a string in a specific format, making it easier to read and understand. The method uses placeholders, which are enclosed in curly braces {}, to indicate where values should be inserted into the string.

Basic Usage

To use Python format, you simply need to create a string with placeholders and then pass values to the placeholders using the format method. Here is an example:

name = "John" age = 25 print("My name is {} and I am {} years old.".format(name, age))

The output of this code would be:

My name is John and I am 25 years old.

In this example, we created a string with two placeholders ({}) and then passed two values (name and age) to the format method. The method replaced the placeholders with the values, resulting in a formatted string.

Positional Arguments

You can also specify the position of the values you want to insert into the string, using positional arguments. Here is an example:

print("My name is {1} and I am {0} years old.".format(age, name))

The output of this code would be:

My name is John and I am 25 years old.

In this example, we specified the position of the values we wanted to insert into the string using the format method. The method replaced the placeholders with the values in the specified positions, resulting in a formatted string.

Named Arguments

You can also use named arguments to insert values into a string. Here is an example:

print("My name is {name} and I am {age} years old.".format(name="John", age=25))

The output of this code would be:

My name is John and I am 25 years old.

In this example, we used named arguments to insert values into the string. We specified the names of the arguments in the placeholders and then passed the values to the format method using keyword arguments.

Formatting Values

Python format also allows you to format values before inserting them into a string. Here are some examples:

Floating Point Numbers pi = 3.14159265359 print("The value of pi is approximately {:.2f}.".format(pi))

The output of this code would be:

The value of pi is approximately 3.14.

In this example, we formatted the floating point number pi to two decimal places using the format method.

Integers num = 12345 print("The value of num is {:,}.".format(num))

The output of this code would be:

The value of num is 12,345.

In this example, we formatted the integer num to include commas using the format method.

Dates import datetime today = print("Today's date is {:%B %d, %Y}.".format(today))

The output of this code would be:

Today's date is August 01, 2023.

In this example, we formatted the datetime object today to display the month, day, and year in a specific format using the format method.

Padding and Alignment

You can also use the format method to control padding and alignment. For example, you can left-align, right-align, or center-align text within a given width, and pad it with specific characters.

text = "example" print("Left-aligned: {:<10}".format(text)) print("Center-aligned: {:^10}".format(text))

The output of this code would be:

Left-aligned: example Right-aligned: example Center-aligned: example Conclusion

Python format is a powerful method that allows you to create formatted strings that are more readable and easier to work with. It provides several options for inserting values into a string, including positional and named arguments, and allows you to format values before inserting them. By using Python format, you can make your code more user-friendly and easier to maintain.

Using The Main() Function In Python

The main function is not required for every Python program, but it is recommended to use it for better organization and readability of the code. It is especially useful for larger programs where there are multiple functions and classes.

How to Use the Main Function

To use the main function in Python, you need to define it in your program. The main function can have any name, but it is conventionally named main. The main function can also take arguments, but it is not required.

Here is an example of a simple Python program that uses the main function:

def main(): print("Hello, World!") if __name__ == "__main__": main()

In this program, we define the main function that prints the string “Hello, World!” to the console. We then use the if __name__ == "__main__": statement to check if the program is being run as the main program. If it is, we call the main function.

The if __name__ == "__main__": statement is used to check if the module is being run as the main program. This is required because sometimes you may want to import a module into another program, and you don’t want the code in the main function to be executed.

Here are a few more examples of how to use the main function in Python:

Example 1: Taking Command-Line Arguments import sys def main(): name = sys.argv[1] print(f"Hello, {name}!") else: print("Hello, World!") if __name__ == "__main__": main()

In this program, we import the sys module to access the command-line arguments. We then check if there are any arguments passed to the program using len(sys.argv). If there is at least one argument, we print a personalized string. Otherwise, we print “Hello, World!”.

To run this program with a command-line argument, you can run the following command:

python chúng tôi John

This will print “Hello, John!” to the console.

Example 2: Using Classes class Person: def __init__(self, name): chúng tôi = name def say_hello(self): print(f"Hello, {}!") def main(): person = Person("John") person.say_hello() if __name__ == "__main__": main()

In this program, we define a Person class that has a name attribute and a say_hello method. We then create a Person object with the name “John” and call the say_hello method.

Example 3: Using Modules import my_module def main(): my_module.say_hello() if __name__ == "__main__": main()

In this program, we import a module named my_module that contains a say_hello function. We then call the say_hello function from the main function.

Example 4: Using Libraries import requests def main(): print(response.status_code) if __name__ == "__main__": main()

In this program, we import the requests library to make a GET request to Google’s homepage. We then print the status code of the response.

Example 5: Using Context Managers with open("file.txt", "w") as f: f.write("Hello, World!") def main(): with open("file.txt", "r") as f: print( if __name__ == "__main__": main()

In this program, we use a context manager to open a file named “file.txt” in write mode and write “Hello, World!” to it. We then use another context manager to open the same file in read mode and print its contents.


Formatting Containers Using Format() In Python

When using Python, container style can be a useful means of enhancing the readability and maintainability of code. You can style lists, tuples, dictionaries, sets, and even classes quickly and simply using this method. You can adjust how your data is presented by aligning columns, adding padding, and setting accuracy by using the built-in format() method. In this article, we’ll take a deep dive into container formatting using format() in Python, including various types of containers and how to use them with the format() function.

Container Formatting with format()

Assuming we have a list of numbers that we want to organize by separating each number with a comma and a space.


my_list = [1, 2, 3, 4, 5] formatted_list = ', '.join(['{}'.format(x) for x in my_list]) print(formatted_list) Output 1, 2, 3, 4, 5

The collection of formatted numbers with a comma and space separator is joined using the join() method in this case. Each integer value in the enumeration will substitute the ” placeholder inside the format() method.

Although immutable, tuples are comparable to lists in that their contents cannot be altered once they have been formed. In this case, we joined the formatted tuple components with a comma and space using the join() method once more

Example my_tuple = ('apple', 'banana', 'orange') formatted_tuple = ', '.join(['{}'.format(x) for x in my_tuple]) print(formatted_tuple) Output apple, banana, orange

By combining dictionary values and the format() method, dictionaries can be formatted.

Example my_dict = {'name': 'ABCJohn', 'age': 33, 'city': 'Los Angeles'} formatted_dict = 'Name: {name}, Age: {age}, City: {city}'.format(**my_dict) print(formatted_dict) Output Name: ABCJohn, Age: 33, City: Los Angeles

In this case, we used format() method placeholders that matched the values in our dictionary. The dictionary is unpacked using the **my dict syntax, and its contents are then passed as keyword parameters to the format() method. Similarly, sets can be written inside of a set comprehension by using the join() and format() functions.

Example my_set = {1, 2, 3, 4, 5} formatted_set = ', '.join(['{}'.format(x) for x in my_set]) print(formatted_set) Output 1, 2, 3, 4, 5

Same can be done for Classes

Example class Person: def __init__(self, name, age): chúng tôi = name chúng tôi = age my_person = Person('John', 30) formatted_person = 'Name: {}, Age: {p.age}'.format(p=my_person) print(formatted_person) Output Name: John, Age: 30

Passing an instance of our class as a keyword argument to the format() function is a viable solution

Customization Options

In addition to formatting containers, the format() function also provides options to customize how the data is displayed. Some common options include padding, alignment, and precision.

my_list = ['apple', 'banana', 'orange']

We can format this list so that each string is right-aligned in a field of width 10 using the following code −

Example my_list = ['apple', 'banana', 'orange'] for fruit in my_list: Output apple banana orange

The < option and the ^ option can be used to centre and left-align the lines within the box, respectively. The precision selection, which enables us to choose how many numbers are presented after the decimal point, is another helpful choice. Consider a collection of floating-point values as an illustration −

my_floats = [1.23456, 2.34567, 3.45678]

We can format these numbers to display only two digits after the decimal point using the following code −

Example my_floats = [1.23456, 2.34567, 3.45678] for num in my_floats: print('{:.2f}'.format(num)) Output 1.23 2.35 3.46

Additionally, we can use f-strings and other text editing methods in conjunction with format(). This enables us to design output lines that are more intricate and flexible. Let’s look at a full code block that exemplifies container formatting in Python now that we know how to style containers with format().


my_dict = {'apple': 1.23, 'banana': 2.34, 'orange': 3.45} for key, value in my_dict.items(): print('{:<10}{:.2f}'.format(key, value)) Output apple 1.23 banana 2.34 orange 3.45

By using this code block, a dictionary is created that links the titles of three fruits to their corresponding values. The for loop loops through the dictionary’s entries iteratively, formatting each key-value combination so that the value is shown with two digits after the decimal point and the key is left-aligned in a field with a width of 10. Container editing with format() has many applications in real-world settings. For instance, we might employ it to style tables or diagrams during data analysis. It may be used in web programming to present material in a user-friendly manner. We might use it in automation to produce records or files.


In summation, container formatting with Python’s format() function is a strong instrument that enables us to present data in a flexible and comprehensible manner. We can produce content that is specific to our requirements by using the format() function with a range of container kinds and formatting choices. I trust that this piece has helped you comprehend container formatting in Python, and I invite you to learn more about it on your own.

Creating Interactive Visualizations Using Plotly In Python


In today’s world, every second the data keeps on getting bigger and bigger. In order to understand the data quickly and to draw insights, data visualization becomes necessary.

For e.g. consider a case where you are asked to illustrate crucial sales aspects (like sales performance, target, revenue, acquisition cost, etc.) from huge amounts of sales data, which one would you prefer:

Exploring the data using different types of sales graphs and charts

Obviously, you would prefer graphs and charts. So data visualization plays a key role in data exploration and data analysis.

Data Visualization is the technique to represent the data/information in a pictorial or graphical format. It enables the stakeholders and decision-makers to analyze and explore the data visually and uncover deep insights.

“Visualization gives you answers to questions you didn’t know you had.” – Ben Schneiderman

Benefits of Data Visualization

Helps in data analysis, data exploration and makes the data more understandable.

Summarises the complex quantitative information in a small space.

Helps in discovering the latest trends, hidden patterns in the data.

Identifies the relationships/correlations between the variables.

Helps in examining the areas that need attention or improvement.

Why Plotly?

There are several libraries available in Python like Matplotlib, Seaborn, etc. for data visualization. But they render only the static images of the charts/plots and due to this, many crucial things get lost in the visualization. Wouldn’t it be amazing if we could interact better with the charts by hovering in (or) zooming in? Plotly allows us to do the same.

Plotly is an open-source data visualization library to create interactive and publication-quality charts/graphs.

Plotly offers implementation of many different graph types/objects like line plot, scatter plot, area plot, histogram, box plot, bar plot, etc.

Plotly supports interactive plotting in commonly used programming languages like Python, R, MATLAB, Javascript, etc.

In this post, we will cover the most commonly used graph types using Plotly. So let’s get started using the Cars93 dataset available on Kaggle.

The dataset contains 27 car parameters (like manufacturer, make, price, horsepower, engine size, weight, cylinders, airbags, passengers, etc.) of 93 different cars.

The dataset looks like this:

Installing Plotly

In order to install Plotly, use the following command in the terminal.

pip install plotly

Plotly comes with few modules to create visualizations, i.e. giving us a choice of how to utilize it.

express: A high-level interface for creating quick visualizations. It’s a wrapper around Plotly graph_objects module.

graph_objects: A low-level interface to figures, traces, and layouts. It’s highly customizable in general for different graphs/charts.

figure_factory: Figure Factories are dedicated functions for creating very specific types of plots. It was available prior to the existence of Plotly express, therefore deprecated as “legacy”.

Having known and installed Plotly, now let’s plot different graphs/charts using it.

1. Box Plot

A box plot (or box-and-whisker plot) is a standardized way to display the distribution of quantitative data based on a Five-Point summary (minimum, first quartile(Q1), median(Q2), third quartile(Q3), and maximum).

The box extends from the Q1 to Q3 quartile values, whereas the whiskers extend from the edges of the box to the 1.5*IQR. IQR = (Q3 – Q1)

The best thing about this visualization is that we can start interacting with it by hovering in to see the quantiles values.

Similarly, we can customize it as per the requirement. For e.g. drawing a boxplot of Price for each AirBags type.

2. Histogram

A histogram is an accurate representation of the distribution of numerical data.

To construct a histogram, follow these steps −


(or bucket) the range of values – Divide the entire range of values into a series of intervals.


how many values fall into each interval.

Let’s draw a histogram for cars’ Horsepower feature.

Here, X-axis is about bin ranges of Horsepower whereas Y-axis talks about frequency/count in each bin.

3. Density Plot

The density plot is a variation of a histogram, where instead of representing the frequency on the Y-axis, it represents the PDF (Probability Density Function) values.

It’s helpful in determining the Skewness of the variable visually.

Also, useful in assessing the importance of a continuous variable for a classification problem.

The density plot of Horsepower based on AirBags type is as shown below.

4. Bar Chart

A bar chart represents categorical data with rectangular bars with weights proportional to the values that they represent.

A bar plot shows comparisons among discrete categories.

The bar chart of the Type feature is as shown below.

Similarly, we can customize it to display mean on the Y-axis, instead of displaying count.

5. Pie Chart

Pie Chart is used to represent the numerical proportion of the data in a circular graph.

The whole area of the chart represents 100% of the data, the arc length of each slice represents the relative percentage part of the whole.

The pie chart of the Type feature is as shown below.

6. Scatter Plot

A scatter plot uses dots to represent values for two different numeric variables.

It is really helpful in observing the relationship between two numeric variables.

Let’s draw a scatter plot, in order to assess the relationship between Horsepower and

From this plot, we can observe that as the Horsepower increases, MPG in the city decreases.

Plotly also provides a way to draw 3D scatter plots. Let’s draw the same using Horsepower,, and Price features.

Similarly, we can draw a scatter plot matrix (a grid/matrix of scatter plots) to assess pairwise relationships for each combination of variables.

7. Line Chart

A line chart is a type of chart that displays information as a series of data points called ‘markers’ connected by straight line segments.

It is similar to a scatter plot except that the measurement points are ordered (typically by their x-axis value) and joined with straight line segments.

Line graphs are usually used to find relationships between two numeric variables or to visualize a trend in time series data.

Let’s draw a scatter plot, in order to assess the relationship between Horsepower and

8. Heatmap

A heatmap is a two-dimensional graphical representation of data whereas matrix values are represented in different shades of colors.

A heatmap aims to provide a color-coded visual summary of data/information.

Seaborn allows annotated heatmaps as well.

Let’s draw a heatmap to represent the correlation matrix of cars93 data.

9. Violin Plot

Violin plots are similar to box plots, except that they also show the probability density of the data at different values. In other words, the violin plot is a combination of a box plot and density plot.

Broader sections of the violin plot indicate higher probability, whereas the narrow sections indicate lower probability.

The Violin plot of the Price feature is shown below.

Similarly, we can customize it using Plotly to display the box and all the data points.

10. Word Cloud

Word Cloud is a visualization technique to represent the frequency of words within a given text segment.

The size of a word indicates how frequently it occurs in the text. The bigger the size, the greater the importance(frequency), whereas the smaller the size, the lesser the importance(frequency).

Word clouds are often used for representing the frequency of words within text documents, reports, website data, public speeches, etc.

Word cloud of a chosen text document is as shown below.

End Notes

The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion. 


Build A Voice Recorder Using Python

This article was published as a part of the Data Science Blogathon

A voice recorder records a sound or a voice of a person and converts it into an audio file. The file can be stored in different audio formats like MP3 format, Waveform Audio File (WAV), Advanced Audio Coding (AAC), Audio Interchange File Format (AIFF), etc. and later it can be transferred to other devices. Any device that is capable of recording a sound or a voice is said to be a voice recorder by default.

In this article, you will learn to build a voice recorder with few lines of code in Python.

Where do we use Voice Recorder?

Some of the applications of a voice recorder are listed below,


Handling Meetings

Lectures/Seminars in Educational Institutions

Audiobooks for kids

Learning foreign languages

Translating a word to another language

Google search by voice

A quick voice message to a person instead of typing


Voice assistants like Google assistants, Alexa, Siri, etc.,

Essentials of Voice Recorder using Python

The first and foremost thing needed to build a voice recorder using Python is 2 basic Python modules. They are,

sounddevice module

write module from


The two modules needed to code a voice recorder must be installed first to make use of it in a program further. If you are using conda as the package manager like Miniconda or Anaconda for OS like Linux, Windows or macOS, then you can install using conda-forge channel. The command for installation is as follows,

conda install -c conda-forge python-sounddevice

These Python modules can also be installed using the command, 

pip install sounddevice


python -m pip install sounddevice

Installation of SciPy module in your device can be made by using the following command,

pip install scipy


python -m pip install scipy

To uninstall a module, specify the command as,

python3 -m pip uninstall sounddevice sounddevice module to build Voice Recorder Using Python

The sounddevice module in Python has functions to play and record audio signals contained in the NumPy array. It can also provide bindings for the PortAudio library.

If you install the sounddevice module using the above pip command on Windows or macOS, then it automatically installs the PortAudio library on your device. You need to install the PortAudio library with other packages manually, only on other Operating Systems rather than the platforms mentioned above. module

It writes the NumPy array into a WAV file. The WAV file will be simple and compressed. It takes 3 parameters namely, filename, sample rate, and data. To make multiple channels, use a 2D array of shapes.

Some of the functions carried out by this module are,



Simultaneous Playback and Recording

Selection of a particular device

Callback Streams

Block read/write streams

Importing modules

The above modules need to be imported first to extract all its features and to be used inside our program. It can be imported with the help of the following commands,

import sounddevice from import write Record an audio

The sounddevice.rec() method from the sounddevice module is used to record audio data from a sound device into an array in NumPy. The sampling frequency is assigned by the programmer as 44100 frames per second.

The command to record audio is as follows,

record_voice = chúng tôi int( second * fs ) , samplerate = fs , channels = 2 )

where second → the time duration is taken to record an audio

fs → sampling frequency

The recording will be carried out in the background, so you can work on other commands in the meantime. To check whether the recording is finished, use the command as,


By default, the data type of the recorded array will be float32, you can change the datatype by specifying the command as,

record_voice= sounddevice.rec(second* fs, dtype='float64') Selection of a device

One can have one or more input and output devices connected to their computer so that its user’s wish to select a device from the list of devices connected.

To get the list of devices connected to your device, use the command as


To set a particular device as a default one, use the command as

sounddevice.default.device = 'digital output' Writing into a file

The audio recorded is finally written into a file, where one can fetch or share that file for future use. write() method in Python is used to create a file with filename passed as an argument. The file name must be specified with the extension of an audio format so that it won’t crash with the input given.

The command to write the output into a file is as follows,

write("out.wav", fs , record_voice )

where chúng tôi is the name of the output file. This output file will be saved in the same directory where the program code is saved.

Other methods in sounddevice module

Some of the functions handled by the sounddevice module in Python are,

Usage Function Name Function Description

Playback myarray , fs ) This function plays audio data contained in a NumPy array. It also plays audio in the background.


It stops the playback.

sounddevice.wait() It waits until the playback gets finished.


record_voice = sounddevice.rec(int(seconds * fs), samplerate=fs, channels=2)

Records the audio given as an input.

Concurrent Playback and Recording sounddevice.playrec(myarray, fs, channels=2)

It records and playback audio data at the same time.

Stream Callback get_status()

Results in the status of the device, whether it is still recording or finished recording.

get_stream() It results in a stream whether the device is in the Input stream or the device is in the Output stream.

Blocking Streams

It blocks the read stream.


It blocks the write stream.

Building a Voice Recorder in Python import sounddevice from import write fs= 44100 second = int(input("Enter time duration in seconds: ")) print("Recording.....n") record_voice = chúng tôi int ( second * fs ) , samplerate = fs , channels = 2 ) sounddevice.wait() write("out.wav",fs,record_voice) print("Finished.....nPlease check your output file") Conclusion

Hope you guys found an easy and informative article on creating Voice Recorder with the help of Python. Thanks for spending your valuable time here.

Happy learning!

Love Conquers All…!

About the author

Am Venkatalakshmi Subramaniam from Manchester of South India, am a passionate blogger, author as well as a doctoral student eager to learn new things day by day. 

Connect with me via 

The media shown in this article are not owned by Analytics Vidhya and are used at the Author’s discretion.


Update the detailed information about Using The Append() Method In Python on the website. We hope the article's content will meet your needs, and we will regularly update the information to provide you with the fastest and most accurate information. Have a great day!