Deploying Python Applications with Gunicorn

Deploying Python Applications with Gunicorn
Hostman Team
Technical writer
Python
23.10.2024
Reading time: 7 min

In this article, we’ll show how to set up an Ubuntu 20.04 server and install and configure the components required for deploying Python applications. We’ll configure the WSGI server Gunicorn to interact with our application. Gunicorn will serve as an interface that converts client requests via the HTTP protocol into Python function calls executed by the application. Then, we will configure Nginx as a reverse proxy server for Gunicorn, which will forward requests to the Gunicorn server. Additionally, we will cover securing HTTP connections with an SSL certificate or using other features like load balancing, caching, etc. These details can be helpful when working with cloud services like those provided by Hostman.

Creating a Python Virtual Environment

To begin, we need to update all packages:

sudo apt update

Ubuntu provides the latest version of the Python interpreter by default. Let’s check the installed version using the following command:

python3 --version

Example output:

Python 3.10.12

We’ll set up a virtual environment to ensure that our project has its own dependencies, separate from other projects. First, install the virtualenv package, which allows you to create virtual environments:

sudo apt-get install python3-venv python3-dev

Next, create a folder for your project and navigate into it:

mkdir myapp
cd myapp

Now, create a virtual environment:

python3 -m venv venv

And create a folder for your project:

mkdir app

Your project directory should now contain two items: app and venv.

You can verify this using the standard Linux command to list directory contents:

ls

Expected output:

myapp venv

You need to activate the virtual environment so that all subsequent components are installed locally for the project:

source venv/bin/activate

Installing and Configuring Gunicorn

Gunicorn (Green Unicorn) is a Python WSGI HTTP server for UNIX. It is compatible with various web frameworks, fast, easy to implement, and uses minimal server resources.

To install Gunicorn, run the following command:

pip install gunicorn

WSGI and Python

WSGI (Web Server Gateway Interface) is the standard interface between a Python application running on the server side and the web server itself, such as Nginx. A WSGI server interacts with the application, allowing you to run code when handling requests. Typically, the application is provided as an object named application in a Python module, which is made available to the server.

In the standard wsgi.py file, there is usually a callable application. For example, let’s create such a file using the nano text editor:

nano wsgi.py

Add the following simple code to the file:

from aiohttp import web

async def index(request):
    return web.Response(text="Welcome home!")

app = web.Application()
app.router.add_get('/', index)

In the code above, we import aiohttp, a library that provides an asynchronous HTTP client built on top of asyncio. HTTP requests are a classic example of where asynchronous handling is ideal, as they involve waiting for server responses, during which other code can execute efficiently. This library allows sequential requests to be made without waiting for the first response before sending a new one. It’s common to run aiohttp servers behind Nginx.

Running the Gunicorn Server

You can launch the server using the following command template:

gunicorn [OPTIONS] [WSGI_APP]

Here, [WSGI_APP] consists of $(MODULE_NAME):$(VARIABLE_NAME) and [OPTIONS] is a set of parameters for configuring Gunicorn.

A simple command would look like this:

gunicorn wsgi:app

To restart Gunicorn, you can use:

sudo systemctl restart gunicorn

Systemd Integration

systemd is a system and service manager that allows for strict control over processes, resources, and permissions. We’ll create a socket that systemd will listen to, automatically starting Gunicorn in response to traffic.

Configuring the Gunicorn Service and Socket

First, create the service configuration file:

sudo nano /etc/systemd/system/gunicorn.service

Add the following content to the file:

[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
Type=notify
User=someuser
Group=someuser
RuntimeDirectory=gunicorn
WorkingDirectory=/home/someuser/myapp
ExecStart=/path/to/venv/bin/gunicorn wsgi:app
ExecReload=/bin/kill -s HUP $MAINPID
KillMode=mixed
TimeoutStopSec=5
PrivateTmp=true

[Install]
WantedBy=multi-user.target

Make sure to replace /path/to/venv/bin/gunicorn with the actual path to the Gunicorn executable within your virtual environment. It will likely look something like this: /home/someuser/myapp/venv/bin/gunicorn.

Next, create the socket configuration file:

sudo nano /etc/systemd/system/gunicorn.socket

Add the following content:

[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock
SocketUser=www-data

[Install]
WantedBy=sockets.target

Enable and start the socket with:

systemctl enable --now gunicorn.socket

Configuring Gunicorn

Let's review some useful parameters for Gunicorn in Python 3. You can find all possible parameters in the official documentation.

Sockets

  • -b BIND, --bind=BIND — Specifies the server socket. You can use formats like: $(HOST), $(HOST):$(PORT).

Example:

gunicorn --bind=127.0.0.1:8080 wsgi:app

This command will run your application locally on port 8080.

Worker Processes

  • -w WORKERS, --workers=WORKERS — Sets the number of worker processes. Typically, this number should be between 2 to 4 per server core.

Example:

gunicorn --workers=2 wsgi:app

Process Type

  • -k WORKERCLASS, --worker-class=WORKERCLASS — Specifies the type of worker process to run.

By default, Gunicorn uses the sync worker type, which is a simple synchronous worker that handles one request at a time. Other worker types may require additional dependencies.

Asynchronous worker processes are available using Greenlets (via Eventlet or Gevent). Greenlets are a cooperative multitasking implementation for Python. The corresponding parameters are eventlet and gevent.

We will use an asynchronous worker type compatible with aiohttp:

gunicorn wsgi:app --bind localhost:8080 --worker-class aiohttp.GunicornWebWorker

Access Logging

You can enable access logging using the --access-logfile flag.

Example:

gunicorn wsgi:app --access-logfile access.log

Error Logging

To specify an error log file, use the following command:

gunicorn wsgi:app --error-logfile error.log

You can also set the verbosity level of the error log output using the --log-level flag. Available log levels in Gunicorn are:

  • debug

  • info

  • warning

  • error

  • critical

By default, the info level is set, which omits debug-level information.

Installing and Configuring Nginx

First, install Nginx with the command:

sudo apt install nginx

Let’s check if the Nginx service can connect to the socket created earlier:

sudo -u www-data curl --unix-socket /run/gunicorn.sock http

If successful, Gunicorn will automatically start, and you'll see the HTML code from the server in the terminal.

Nginx configuration involves adding config files for virtual hosts. Each proxy configuration should be stored in the /etc/nginx/sites-available directory.

To enable each proxy server, create a symbolic link to it in /etc/nginx/sites-enabled. When Nginx starts, it automatically loads all proxy servers in this directory.

Create a new configuration file:

sudo nano /etc/nginx/sites-available/myconfig.conf

Then create a symbolic link with the command:

sudo ln -s /etc/nginx/sites-available/myconfig.conf /etc/nginx/sites-enabled

Nginx must be restarted after any changes to the configuration file to apply the new settings.

First, check the syntax of the configuration file:

nginx -t

Then reload Nginx:

nginx -s reload

Conclusion

Gunicorn is a robust and versatile WSGI server for deploying Python applications, offering flexibility with various worker types and integration options like Nginx for load balancing and reverse proxying. Its ease of installation and configuration, combined with detailed logging and scaling options, make it an excellent choice for production environments. By utilizing Gunicorn with frameworks like aiohttp and integrating it with Nginx, you can efficiently serve Python applications with improved performance and resource management.

Python
23.10.2024
Reading time: 7 min

Similar

Python

Mastering Python For Loops: An Essential Guide

Loops are a significant aspect of programming languages. Python for loop is a simple and easy way to repeat actions which are in sequence on each item. Whether it is to process characters in string, iterate through the list, or generate numeric ranges, any type of repetitive task can be done easily and efficiently. The following guide walks through their usage with syntax, examples, and day-to-day applications. A Python for loop simplifies iteration by automatically traversing elements within collections like lists, tuples, dictionaries, strings, or ranges. Instead of relying on a manual index like in some other languages, Python loops directly interact with the elements of the collection, making them more intuitive and there is a lower possibility of errors. Breaking down the flow of a for loop can help in understanding its mechanics. Consider this sequence of steps: Start -> Initialize -> Condition Check -> Execute Block -> Increment -> Repeat -> End Structure and syntax This section discusses structure and syntax of for loops by performing a few simple examples.  Structure Below is representation of the simple structure of a for loop in Python: for variable in iterable: # Code block to execute variable: Temporary variable that represents every element of the sequence. iterable: Collection to iterate over (e.g., a list or range). Code block: Indented block of code executed for every iteration. Example: fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit) Output: apple banana cherry Utilizing range() for Numerical Loops When numeric values need to be generated in a sequence, the range() function proves invaluable. It offers a convenient method to produce numbers within a defined range, with the option to skip values using a specified step. Syntax: range(start, stop, step) start: Beginning of sequence (default is 0). stop: Endpoint, excluded from the range. step: Increment or decrement applied between consecutive values (default is 1). Example: for i in range(1, 6): print(i) Output: 1 2 3 4 5 Use Cases and Practical Examples of Python For Loops Dealing with Strings Strings can be easily iterated using a for loop, making it useful for tasks like counting characters or modifying text. Example: text = "Python" for char in text: print(char) Output: P y t h o n Combining Nested For Loops In the scenario of dealing with nested structures which include multidimensional lists or grids, nested for loops are a handy solution. A loop within another loop ensures that every element is addressed at each hierarchy level. Example: matrix = [[1, 2], [3, 4], [5, 6]] for row in matrix: for item in row: print(item) Output: 1 2 3 4 5 6 Dealing with Dictionaries Dictionaries are easily looped through by utilizing a for loop in Python. You can iterate over values, keys, or both by using for loops. Example: student_scores = {"Alice": 85, "Bob": 78, "Charlie": 92} # Looping through keys for student in student_scores: print(student) # Looping through values for score in student_scores.values(): print(score) # Looping through keys and values for student, score in student_scores.items(): print(f"{student}: {score}") This makes working with dictionaries simple and efficient, whether you need just the keys, the values, or both in a single loop. Controlling Loop Flow with break and continue Another method to further refine a for loop is by utilizing the statements break and continue: Break: In this scenario, a condition must be satisfied so that the loop can exit prematurely. Continue: It will skip current iteration and proceed to next. Example demonstrating break: for num in range(10): if num == 5: break print(num) Output: 0 1 2 3 4 Example demonstrating continue: for num in range(10): if num % 2 == 0: continue print(num) Output: 1 3 5 7 9 Summation of Values in List Here’s an example of using for loops to sum numbers in a list. numbers = [10, 20, 30, 40] total = 0 for num in numbers: total += num print("Total:", total) Output: Total: 100   Creating Multiplication Tables With the help of nested for loops, complete multiplication table which showcases the product of two numbers in a structured format can be generated. for i in range(1, 6): for j in range(1, 6): print(f"{i} x {j} = {i * j}") print() Output: 1 x 1 = 1 1 x 2 = 2 ... Reading Files Line by Line Reading a file line by line with a for loop is memory efficient, as it processes the file without loading it entirely into memory, reducing computational power. Example: with open("example.txt", "r") as file: for line in file: print(line.strip()) # Strips leading/trailing whitespaces Here, the for loop in Python will iterate through each line in the file, and will print each one after removing extra spaces. The method is memory efficient and works well for large text files. Enhancing the Readability of Your Code Python's for loop syntax is efficient, simple, and enhances code readability by allowing focus on the task rather than access mechanics, reducing errors. Example: # Without a for loop print(“1”) print(“2”) print(“3”) # With a for loop numbers = [1, 2, 3] for number in numbers: print(number) Notice how the second method is more straightforward and readable. Complex Data Structures For loops are flexible enough to handle more advanced collections like sets, dictionaries, and even custom objects. The iteration is seamless over these structures due to for loops and there is no need for any additional logic. Example: # Iterating Through a Dictionary student_scores = {"Alice": 85, "Bob": 78, "Charlie": 92} # Access keys for student in student_scores: print(student) # Access values for score in student_scores.values(): print(score) # Access both keys and values for student, score in student_scores.items(): print(f"{student}: {score}") The above example shows the easiness of extracting specific elements as well as combinations of those elements. For Loops in Real-Life Programming For loops aren’t just theoretical; they play an important role in handling real-world processes like processing files, analyzing data, and automating repetitive actions. Example: # Reading Lines from a File with open("example.txt", "r") as file: for line in file: print(line.strip()) In case one has to work with large datasets stored in text files then this approach is much practical. Using Enumerate for Indexed Iteration Enumerate is best suited for when the index and value, both, of each element are needed. Writing extra code to manage counters is not required anymore. Its much time efficient. Example: # Enumerating Elements fruits = ["apple", "banana", "cherry"] for index, fruit in enumerate(fruits): print(f"{index}: {fruit}") This method is concise and reduces the chance of errors. Making Loops Error-Proof By adding error-handling mechanisms, you can be sure that your loops are resilient and have ability to handle unexpected scenarios gracefully. Example: # Handling Errors in Loops numbers = [10, 20, "a", 30] for num in numbers: try: print(num * 2) except TypeError: print(f"Skipping invalid type: {num}") This approach works great when one has to deal with unpredictable data. Other Iteration Techniques While for loops are versatile, some tasks might benefit from alternative approaches like list comprehensions or generator expressions. These are often more concise and better suited for specific scenarios. Example: # Using List Comprehension # Traditional for loop squares = [] for num in range(5): squares.append(num ** 2) print(squares) # List comprehension squares = [num ** 2 for num in range(5)] print(squares) Both approaches achieve the same result, but list comprehensions are much compact. Performance Tips for For Loops Although for loops have been more practical for huge amount of queries, large-scale operations might require faster alternatives like NumPy which are best for numerical data. Example: # Using for loop large_list = list(range(1000000)) squared = [num ** 2 for num in large_list] # Using NumPy (faster) import numpy as np large_array = np.array(large_list) squared = large_array ** 2 This comparison highlights that libraries actually significantly boost performance. Summary For loops in Python are proven to be highly advantageous and versatile when it comes to handling repetitive tasks across various data structures. From simple iterations to complex nested loops, understanding their potential unlocks efficiency in programming. Practice these examples and experiment with your own to master this essential concept. If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman.
25 December 2024 · 7 min to read
Python

How to Use f-strings in Python

Python f-strings, introduced in Python 3.6, revolutionized how developers format strings. These possess abilities of being precise, readable, & highly powerful which makes these a preferred method for string interpolation in Python. This manual covers all that there is so that you learn about all the different aspects about f-strings of python. It covers basic usage & goes all the way to advanced formatting techniques. Introduction Formatting a string is an integral part of programming in Python, helping developers to dynamically include data within strings. Among different processes of formatting strings, f-strings stand out because of their simplicity and performance benefits. f-strings are also known as formatted string literals. First came out  in Python 3.6, f-strings blend flexibility & efficiency, making them a go-to choice for many developers. This manual will provide a detailed elaboration of f-strings, covering their syntax, features, & practical applications. By the end, you will be an expert in using f-strings effectively. It also proves much efficient for your code & is also better readable. f-strings are also called formatted string literals.These are used for inserting expressions or variables, as well as function outputs directly. For creating an f-string, you can prefix string with either an uppercase or lowercase f. After that whatever will be placed in curly braces {} will be a part of the string. It will also be printed as if it was part of that string. Benefits of f-strings Using f-strings offers numerous benefits, including: Enhanced Readability: Due to these there is seamless embedding of Variables & Expressions into strings Improved Performance: As compared to other techniques that are used for formatting like str.format() or %-based formatting, they have faster performance. Flexibility: Supports nested formatting, calling functions. & calculations. f-strings Syntax Its syntax is very straightforward. f"string with {expression}" Basic syntax example:  name = "Alice" age = 30 greeting = f"My name is {name}, and I am {age} years old." print(greeting) Output: My name is Alice, and I am 30 years old. Core functions of f-strings Let’s dive into the essential features of f-strings. Using Expressions Inside f-strings F-strings not only embed  variables; they also allow the inclusion of any valid Python expression within the curly braces. Example: x = 10 y = 20 result = f"The sum of {x} and {y} is {x + y}." print(result) Output: The sum of 10 and 20 is 30. Formatting of numbers in f-strings Formatted string literals provide an elegant way to display numbers with specific formatting options, like rounding, padding, or converting values to percentages. Example: pi = 3.14159formatted_pi = f"Value of pi: {pi:.2f}"print(formatted_pi) Output: Value of pi: 3.14 Escaping Curly Braces For some cases, curly braces are used in the output text itself. To display literal curly braces in an f-string, use double braces {{ and }}. Example: template = f"Use {{braces}} to include special characters."print(template) Output: Use {braces} to include special characters. Multiline f-strings F-strings can span multiple lines, making them useful for constructing large text blocks while maintaining readability. Example: title = "Python f-strings" description = "powerful, fast, and easy to use" message = f""" Title: {title} Description: f-strings are {description}. """ print(message) Output: Title: Python f-stringsDescription: f-strings are powerful, fast, and easy to use. Nesting and Combining f-strings F-strings can contain other f-strings or be combined with traditional strings. This capability is helpful for dynamic and complex outputs. Example: name = "Bob"info = f"{name.upper()}: {f'Name has {len(name)} characters'}"print(info) Output: BOB: Name has 3 characters Handling Lists and Dictionaries With f-strings, you can directly access elements from lists or keys in dictionaries. Example with Lists: items = ["Python", "JavaScript", "C++"]favorite = f"My favorite programming language is {items[0]}."print(favorite) Output: My favorite programming language is Python. Example with Dictionaries: data = {"name": "Eve", "role": "Developer"}message = f"{data['name']} works as a {data['role']}."print(message) Output: Eve works as a Developer. f-Strings vs. Other string Methods Now, let's compare f-strings with other types of strings methods in python.  % Formatting vs. f-Strings The % operator, an older method, uses placeholders like %s for strings and %d for integers. While functional, it can be cumbersome and error-prone. Example: # % Formatting name = "Alice" age = 25 print("Hello, %s. You are %d years old." % (name, age)) # Equivalent f-string print(f"Hello, {name}. You are {age} years old.") Comparison: % formatting requires tuples and placeholder matching, increasing complexity. Python f-strings embed variables directly, making the code simpler and easier to read. str.format() vs. f-Strings The str.format() method introduced named placeholders, improving readability over % formatting. However, it still requires method calls, which can feel verbose. Example: # str.format() print("Hello, {}. You are {} years old.".format(name, age)) # Equivalent f-string print(f"Hello, {name}. You are {age} years old.") Advanced Example: Named placeholders: # str.format() with named placeholders print("Hello, {name}. You are {age} years old.".format(name=name, age=age)) # Equivalent f-string print(f"Hello, {name}. You are {age} years old.") Comparison: str.format() improves over % formatting but can still feel clunky. f-strings streamline the process, especially for dynamic expressions. String Concatenation vs. f-Strings String concatenation combines strings using the + operator. While straightforward, it becomes inefficient for more complex formatting needs. Example: # String concatenation print("Hello, " + name + ". You are " + str(age) + " years old.") # Equivalent f-string print(f"Hello, {name}. You are {age} years old.") Comparison: Concatenation requires explicit type conversion, increasing verbosity. Python f-strings handle formatting and type conversion automatically. Advanced Example: Including expressions: # String concatenation years_later = 5 print(name + " will be " + str(age + years_later) + " in " + str(years_later) + " years.") # Equivalent f-string print(f"{name} will be {age + years_later} in {years_later} years.") Practical Applications of f-Strings in Python Whether you're crafting dynamic SQL queries, improving logging efficiency, or processing data for analytics, f-strings in Python simplify your workflow and enhance code readability. Generating Dynamic SQL Queries In applications involving databases, f-strings perform really well to construct dynamic SQL queries by embedding variables directly into the query string. Example: # Generating SQL queries using f-strings table_name = "users" condition = "age > 30" sql_query = f"SELECT * FROM {table_name} WHERE {condition};" print(sql_query) # Output: SELECT * FROM users WHERE age > 30; By embedding variables into the SQL query string, f-strings in Python reduce the risk of syntax errors and make the code intuitive. Enhancing Logging Statements Logging plays an important role in debugging and monitoring applications. Python f-strings simplify logging statements, especially at the time at which dynamic data is included. Example: # Logging with f-strings username = "Alice" action = "logged in" print(f"User {username} has {action} at 10:30 AM.") # Output: User Alice has logged in at 10:30 AM. Working with data for analytics purposes Because of the use of f-strings, formatting strings dynamically based on variable content, is possible. This enables efficient and concise manipulation of data. Example: # Processing analytics data metric = "conversion rate" value = 7.5 print(f"The {metric} has increased to {value}%.") # Output: The conversion rate has increased to 7.5%. Crafting Dynamic File Paths Automating the handling of a file often involves dynamically generating file paths. Python f-strings have made this process straightforward. Example: # Generating dynamic file paths directory = "/data/exports" filename = "report_2024.csv" path = f"{directory}/{filename}" print(path) # Output: /data/exports/report_2024.csv Dynamic Web Content Generation During web development, HTML or JSON content can be generated dynamically by the use of f-strings. Example: # Dynamic HTML generation title = "Welcome" content = "This is a demo of Python f-strings in action." html = f"<h1>{title}</h1><p>{content}</p>" print(html) # Output: <h1>Welcome</h1><p>This is a demo of Python f-strings in action.</p> Automating titles of report During reporting or analytics, titles often need to reflect about data that is being processed. f-strings in Python automate this with ease. Example: # Automating report titles report_date = "December 2024" report_title = f"Sales Report - {report_date}" print(report_title) # Output: Sales Report - December 2024 Advanced Formatting Features f-strings are capable of handling alignment, width specifications, or time & date  formatting for creation of cleaner outputs. Example: # Aligning text for name, score in [("Alice", 92), ("Bob", 87)]: print(f"{name:<10} | {score:>5}") # Formatting dates from datetime import datetime now = datetime.now() print(f"Current time: {now:%Y-%m-%d %H:%M:%S}") Debugging Made Easier with f-Strings f-strings are capable of showing error messages in more informative by embedding relevant expressions or variables. Example: value = 42 try: assert value > 50, f"Value {value} is not greater than 50." except AssertionError as e: print(e) Common Errors to Avoid During the use of f-strings, a few common pitfalls include: Forgetting to prefix the string with f: This results in a plain string without any formatting. Incompatible Python versions: Ensure Python 3.6 or newer is installed, as f-strings are not supported in earlier versions. Conclusion F-strings are a robust and versatile tool for string formatting in Python. Whether you need to include variables, perform calculations, or debug your code, f-strings simplify such types of tasks with cleaner syntax & better performance. If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman.
19 December 2024 · 9 min to read
Python

How to Add Elements to an Array in Python

In Python, inserting items into arrays is a frequent task. Arrays hold data of a single type and can be initialized with lists, the array module, or through NumPy. Although Python lacks a native array type, both the array module and the NumPy library offer flexible options for managing arrays. Each approach provides unique methods for inserting elements, based on specific needs. Functions such as append() and extend() allow us to add items to built-in arrays. List comprehension is helpful for generating new arrays. For more complex tasks, NumPy offers tools like append(), concatenate(), and insert() to add elements, particularly when dealing with numerical or structured data. Each approach is useful for specific situations. In this tutorial, we will demonstrate all available techniques for inserting elements into an array in Python. Adding Values to Python's Inbuilt Arrays Python provides different methods for inserting values into its inbuilt arrays. These functions allow us to add items at the start, end, or a specific array position. Let’s go through the following methods to understand how they work and which one fits your needs. Method 1: array.append() append() is a useful array method that lets us insert a single value at the last index of the target array. It modifies the original array: from array import array AuthorsIDs = array('i', [12, 110, 13]) print("Original Array: ") print(AuthorsIDs) print("Modified Array: ") AuthorsIDs.append(140) print(AuthorsIDs) Initially, the AuthorIDs array has 12, 110, and 13 as its elements. Next, we invoke append() on the AuthorIDs array to insert 140 at the last position: Here, we utilize i to assign signed integers to AuthorIDs. Similarly, users can specify type codes like f, u, d, etc. to assign float, Unicode, and double-type data to an array. Method 2: array.extend() Array module offers another useful function extend() that lets us add numerous items at the end of an array. It expands the actual array: from array import array AuthorsIDs = array('i', [12, 110, 13]) print("Original Array: ") print(AuthorsIDs) AuthorsIDs.extend([19, 105, 16]) print("Modified Array: ") print(AuthorsIDs) This time, we extend AuthorsIDs with a sub-array of three items: Method 3: array.insert() insert() is an inbuilt array function that lets us add values at an index of our choice and shift the subsequent entries accordingly. It accepts two arguments a value to be added and an index at which the value will be placed: from array import array AuthorsIDs = array('i', [12, 110, 13]) print("Original Array: ") print(AuthorsIDs) AuthorsIDs.insert(2, 55) print("Modified Array: ") print(AuthorsIDs) Here, we add 55 at the third index of AuthorIDs: Method 4: List Comprehension List comprehension lets us integrate new values with existing ones to create an updated array. It doesn’t alter the actual array; instead, it generates a new array based on the given logic: from array import array AuthorsIDs = array('i', [12, 110, 13]) print("Original Array: ") print(AuthorsIDs) newIDs = [14, 51] AuthorsIDs = array('i', [x for x in AuthorsIDs] + newIDs) print("Modified Array: ") print(AuthorsIDs) The newIDs are successfully merged with the AuthorIDs through list comprehension: Method 5: Plus Operator The plus operator + joins the provided arrays. It enables us to add one or more values to the target array: from array import array AuthorsIDs = array('i', [12, 110, 13]) print("Original Array: ") print(AuthorsIDs) newIDs = array('i', [14, 51, 72]) totalIDs = AuthorsIDs + newIDs print("Modified Array: ") print(totalIDs) The + operator successfully integrates the AuthorsIDs and newIDs arrays while preserving the initial ones: Add Elements to NumPy Array NumPy is a commonly utilized Python library in data science and numerical computing. It aids in handling arrays and executing arithmetic operations. Various functions, including append(), concatenate(), and insert(), can be employed to add values to NumPy arrays. Method 1: numpy.append() The append() method of the numpy module adds elements at the end of an array and retrieves a new array. It lets us insert one or more values to a numpy array. Let's import the NumPy library and invoke append() to add the desired elements to the last of AuthorIDs: import numpy as npy AuthorsIDs = npy.array([12, 110, 13]) print("Original Array: ") print(AuthorsIDs) updatedIDs = npy.append(AuthorsIDs, [140, 31]) print("Modified Array: ") print(updatedIDs) It successfully appends 140 and 31 at the right/last of AuthorsIDs: Method 2: numpy.concatenate() NumPy offers a very useful function named concatenate() that merges multiple numpy arrays. Let’s invoke the concatenate() function to integrate the AuthorIDs with newIDs array: import numpy as npy AuthorsIDs = npy.array([12, 110, 13]) newIDs = npy.array([101, 1, 31]) concatenatedIDs = npy.concatenate((AuthorsIDs, newIDs)) print("Modified Array: ") print(concatenatedIDs) We store the concatenated values in a new array named concatenatedIDs: Method 3: numpy.insert() The numpy.insert() function provides the flexibility to place one or more values at any given index of the target array: import numpy as npy AuthorsIDs = npy.array([1, 103, 41]) print("Original Array: ") print(AuthorIDs) newIDs = npy.insert(AuthorsIDs, 1, 102) print("Modified Array: ") print(newIDs) It successfully appended 102 at the first index of AuthorsIDs: Best Practices When managing arrays in Python, the append() method is utilized to insert a single value to the final index of the array. To include multiple elements, you can employ extend() or the + operator. Additionally, the insert() method enables adding elements at specific positions within the array, making it versatile for various use cases. In contrast, NumPy arrays offer more specialized functions for managing data efficiently. numpy.append() is used for appending data, while numpy.concatenate() merges multiple arrays. numpy.insert() can be used for precise insertions. NumPy functions are generally preferred for tasks involving large datasets or numerical computations due to their better performance and scalability. Conclusion In this tutorial, we demonstrated distinct inbuilt and numpy functions for appending elements to Python arrays. Users can utilize several methods to append values to Python arrays, based on the array type and specific use case. For inbuilt arrays, append(), extend(), and insert() allow easy modifications, while list comprehension and the + operator provide additional flexibility for merging arrays.  When operating with NumPy arrays, append(), concatenate(), and insert() offer advanced functionality, especially for quantitative and data science tasks. For larger datasets or more complex operations, you should prefer NumPy due to its efficiency and performance.  If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman. 
18 December 2024 · 6 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support