×

How to append an Array in Python

A group of objects kept at adjacent memory regions is known as an array. It is a container with a set capacity for a certain number of things, all of which must be the same. Many programming languages, including C/C++, JavaScript, etc., use arrays extensively.

Python's array module can be imported to generate an array. An array can be created by using the syntax array(data type, value list), which takes two arguments: a data type and a value list.

Multiple objects of the same kind can be stored together in an array, which makes it simpler to determine the positions of individual elements by only adding an offset to the base value. Combining the arrays might speed up computation by minimizing the size of the code as a whole. In a single variable, it is used to hold several values. If you have a list of objects that are kept in the appropriate variables

item1 = "Python"
item2 = "Learn”
item3 = "Program"

These arrays may be used to loop across automobiles and locate a specific one.

When we need to alter only certain data values, it is helpful. Python has a module called array that can deal with arrays. The terms listed below will help you comprehend the idea of an array:

Element: The element is anything that is kept inside an array.

Index: Each element's position inside an array is indicated by a numerical index used to locate the element.

Displaying an Array

An array may be defined in many distinct ways and languages. The following are some crucial factors that should be taken into account:

  • The index begins at 0.
  • The index of each element allows us to access it.
  • The array's length determines how many elements it can hold.

Operational Arrays

The following are some of the fundamental operations that an array can support:

Traverse: It prints each piece individually.

Insertion: It inserts an element at the specified index.

Deletion: The element at the specified index is deleted.

Search: It looks up an object using either the provided index or the value.

Update: It makes an element at the specified index current.

An Array may be constructed when adding the array module to the Python application.

from array import *  
arrayName = array(typecode, [initializers])

Accessing array elements

Using their corresponding indices, we may access the items of the array.

Program

import array as arr  
num = arr.array('i', [9, 3, 5, 9])  
print("First element:", num[0])  
print("Second element:", num[1])  
print("Second last element:", num[-1])  

Output:

How to append an Array in Python

Analysis: In the above example, we imported an array, declared a variable called "num" that contains the array's elements, and printed the array's contents by accessing them via the array's indices.

How to modify or include items

Since arrays are variable, it is possible to alter individual elements like lists.

Program

import array as arr  
numbers = arr.array('i', [8, 3, 9, 4, 7, 5])     
# modifying the first element  
numbers[0] = 0     
print(numbers)    # Output: array('i', [0, 3, 9, 4, 7, 5])     
# from the third to the fifth element  
numbers[2:5] = arr.array('i', [9, 4, 7])    
print(numbers)    # Output: array('i', [0, 3, 9, 4, 7, 5])  

Output:

How to append an Array in Python

Analysis: In the example above, an array was imported, and a variable called "numbers" was defined to contain the array's value. You can edit or add items to an array by specifying the specific index of the array where the changes or additions should be made.

Why are arrays implemented in Python?

The use of many arrays speeds up computation. The array can help the code become smaller overall.

How can I remove elements from an array?

The Python del command can remove the elements from an array. We may remove any item from the array by utilizing the indices of a certain element.

Program

import array as arr  
num = arr.array('i', [72, 52, 89, 13, 48])  
del number[2]                           # deleting the third component  
print(number)                           # Output: array('i', [72, 52, 13, 48])

Output:

How to append an Array in Python

Analysis: In the example above, we imported an array and defined a variable called "num" that houses the array's data. Here, we eliminate the third member [3] of the provided array using the del expression.

Determining the length of an array

The number of elements in an array is referred to as the array's length. The total number of elements within this array, expressed as an integer, is what is returned.

Syntax:

len(array_name) 

Concatenating an array

Using the + sign, we can quickly join any two arrays together.

Program

u=arr.array('d',[6,10,41,15,7])  
v=arr.array('d',[37,8])  
w=arr.array('d')  
w=u+v  
print("Array w = ",w)  

Output:

How to append an Array in Python

Analysis: In the above example, we have defined variables with the names "u, v, and w" that contain an array's contents.

Program

import array as arr  
num = arr.array('i', [8, 78, 59, 202])  
print("First element:", num[0])  
print("Second element:", num[1])  
print("Second last element:", num[-1])  

Output:

How to append an Array in Python

Analysis: In the above example, we first imported an array, declared a variable named "num" to contain the array value, and then displayed the items using the array's indices.

The append() method in Python

The append() function in Python adds a new item to the list's end. Changing this list adds an element. The method does not return itself. A list or dictionary that creates a nested list may also include the item. The following describes the method.

Syntax

append(u)

Parameters

u: It might be a string, integer, list, dictionary, etc.

Return

It updates the list rather than returning any value.

To know the functioning of the append() method, let's look at some instances.

Program 1:

# Append() method for Python 
# developing a list  
list = ['9','52','16']  
for u in list:  # list iteration  
    print(u)  
# Adding an element to the list 
list.append(13)    
print("List after adding the element : ",list) # List is being displayed

Output:

How to append an Array in Python

Program 2:

# Append() method for Python   
# developing a list  
list = ['7','10','56']  
for u in list:  # list iteration  
    print(u)  
# Adding an element to the list  
list1 = ['7','45','65','96']  
list.append(list1)    
print("List after appending element : ", list) # List is being displayed

Output:

How to append an Array in Python

Program 3

A nested list is produced by appending additional lists to the list. In this case, a list is extended by two lists, creating a list of lists.

# Append() method for Python 
# developing a list  
list = ['9','12','36']  
for u in list:  # list iteration  
    print(u)  
# Adding of an element to the list  
list2 = ['7','62','45','14']  
list.append(list2)    
# Nested list  
list2.append(['75','19','109']) # Adding one more list  
print("List after adding the element : ", list) # List is being displayed  

Output:

How to append an Array in Python

Python's numpy.append() method

The NumPy package contains the numpy.append() method. Appending means adding something, as the term implies. An existing numpy array can have additional

values added or appended to it using the numpy.append() method. The additional values are added to the end of the array using this method.

When merging two arrays, the numpy append() method is utilized. The original array is not modified, but it returns a new array.

Syntax

numpy.append(arr, values, axis=None)

Parameters:

The append() method takes the following parameters:

1. arr: It's a ndarray. A duplicate of such an array is added to the updated values. This argument is essential to numpy and is required. append() function is used.

2. values: The values that are added to a copy of a ndarray are defined by this parameter. One thing to remember is that, except for the axis, those values must have the same form as the initial ndarray. The values can be of any shape and will flatten before usage if the axis is not provided.

3. axis: The axis along which values are added is defined by this variable. The ndarray and the values are flattened before use when the axis is not provided.

Returns

A copy of ndarray with values added to the axis is what this method delivers.

Program 1:

import numpy as u  
x=u.array([[89, 54, 63], [12, 5, 92], [67, 180, 70]])  
y=u.array([[51, 11, 31], [77, 28, 43], [73, 34, 3]])  
z=u.append(x,y)  
z

Output:

How to append an Array in Python

Analysis:

  • We've imported numpy using the alias u.
  • We've declared the variable 'z' and assigned the result of the u.append() method to it. The u.array() method generated the array "x".
  • Using the same u.array() method, we built another array called "y".
  •  
  • The function has been given the arrays "x" and "y".
  • As a final attempt, we attempted printing the value of arr.

The original array was left unchanged in the output, but the values of both arrays, "x" and "y," were shown in a flattened form.

Program 2:

import numpy as u  
x=u.array([[89, 54, 63], [12, 5, 92], [67, 180, 70]])  
y=u.array([[51, 11, 31], [77, 28, 43], [73, 34, 3]])   
z=u.append(x,y,axis=0)  
z

Output:

How to append an Array in Python

Analysis:

  • We have imported numpy with the alias name 'u'.
  • Using the u.array() method, an array named "x" has been constructed.
  • After that, we used the same u.array() function to construct another array called "y."

The function has been given the arrays "x" and "y," as well as the value "0" for the axis.

  • The value produced by the u.append() method has been assigned to the variable "z," defined.
  •  Our final attempt was to print the value of arr.

The result shows the values of both arrays, i.e., 'a' and 'b', vertically in a single array, but the original array remains unchanged.

Program 3:

import numpy as u  
x=u.array([[89, 54, 63], [12, 5, 92], [67, 180, 70]])  
y=u.array([[51, 11, 31], [77, 28, 43], [73, 34, 3]])  
z=u.append(a,b,axis=1)  
z

Output:

How to append an Array in Python

Related Topics

How to add 2 lists in Python?

In Python, a list is defined as a data structure that contains a sequence of elements. It can contain any kind of data type inside it but in order to concatenate two...

3 minutes read.

List Comprehension in Python

Sometimes we need new lists that are completely based on previously existing lists, so to perform this operation successfully, some of the programming languages come with a syntactic construct known...

5 minutes read.

Python Dictionary pop() method

Python Dictionary pop() method The dictionary.pop() method in removes the specified item and returns an element from a dictionary having the given key. Syntax dictionary.pop(key[, default]) Parameter key – This argument signifies the key which is to...

2 minutes read.

Python String islower() method

Python String islower() method The string.islower() method returns a boolean value true if all cased characters in the string are lowercase and for  any other value is returns false otherwise. Syntax string.islower() Parameter NA Return This...

1 minute read.

Inheritance in Python

Inheritance in Python Object-Oriented Programming provides reusable patterns to the code for restricting the redundancy in development projects. One of the basic principles of Object-Oriented Programming that helps achieve recyclable code...

8 minutes read.

How to Convert A List into String In Python?

How to Convert A List into String In Python? List is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets...

3 minutes read.

Python min() function

Python min() function returns you the minimum value element in an iterable. We can also use this function to determine the smallest value among various arguments passed to this function. We...

4 minutes read.

How to slice a list in python

When working with lists, we face situations where we may need a part of the list from one index to the other. Slicing is one of the simpler ways to...

5 minutes read.

Convert uppercase to lowercase in Python

Python String lower() By using the built-in string lower() method, all the uppercase characters can be converted into lowercase characters in a string, The lowercased string from the given string is returned...

1 minute read.

Python datetime

Python provides a module named datetime to work with the date and time. Sometimes in the real life application development, we need to work with the date and time. The date is...

3 minutes read.

OS Module in Python

What is a module? The Modules are the kind of files that contains python statements and definitions. The module is known by the name of the file followed by the suffix...

8 minutes read.

Anonymous/Lambda Function in Python

Lambda keyword is used to declare an Anonymous function, i.e. a function that does not have any name. It is also called Anonymous functions. In python, normal functions are defined...

3 minutes read.

Python Kwargs Example

In this article, we'll talk about Python's kwargs notion. In Python, kwargs has two stars and passes a variable number of keyworded argument lists to the function, whereas args has...

5 minutes read.

Python Combination

Python Combination Permutations and combinations are the important part of our mathematical tools. We use them often in our Python programs. In this tutorial, we will learn about combinations in Python...

6 minutes read.

How to create a class in python

In any programming language, a class is a user-defined plan or blueprint using which objects or instances of the class are created. You may wonder why we need classes in programming....

5 minutes read.

Python globals() function

Python globals() function The globals() function in Python returns the value of the named attribute of object where the ‘name’ must be a string. Syntax globals() Parameter NA Return This function returns the global symbol table as a dictionary. Example...

1 minute read.

Class and Static Methods in Python

The method is an important concept to learn for every programmer or data analyst. We know that in OOP's concept, each object has its attributes and behaviors defined through methods....

3 minutes read.

Python String strip() method

Python String strip() method The string. strip() method in Python removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to...

1 minute read.

Create First GUI Application using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

Fsolve in Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.