×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Adding elements to an array in Python

By IncludeHelp Last updated : December 21, 2024

Importing array module

An array can be declared by using "array" module in Python.

Syntax to import "array" module:

    import array as array_alias_name

Here, import is the command to import Module, "array" is the name of the module and "array_alias_name" is an alias to "array" that can be used in the program instead of module name "array".

Array declaration

To declare an "array" in Python, we can follow following syntax:

array_name = array_alias_name.array(type_code, elements)

Here,

  • array_name is the name of the array.
  • array_alias_name is the name of an alias - which we define importing the "array module".
  • type_code is the single character value – which defines the type of the array elements is the list of the elements of given type_code.

Adding elements to an array

We can add elements to an array by using Array.insert() and Array.append() methods in Python.

Python program to add elements to an array

# Adding Elements to an Array in Python

# importing "array" modules
import array as arr

# int array
arr1 = arr.array("i", [10, 20, 30])

print("Array arr1 : ", end=" ")
for i in range(0, 3):
    print(arr1[i], end=" ")
print()

# inserting elements using insert()
arr1.insert(1, 40)

print("Array arr1 : ", end=" ")
for i in arr1:
    print(i, end=" ")
print()

# float array
arr2 = arr.array("d", [22.5, 33.2, 43.3])

print("Array arr2 : ", end=" ")
for i in range(0, 3):
    print(arr2[i], end=" ")
print()

# inserting elements using append()
arr2.append(54.4)

print("Array arr2 : ", end=" ")
for i in arr2:
    print(i, end=" ")
print()

Output

Array arr1 :  10 20 30
Array arr1 :  10 40 20 30
Array arr2 :  22.5 33.2 43.3
Array arr2 :  22.5 33.2 43.3 54.4

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.