Home » Python

Adding elements to an array in Python

Various methods to insert elements in an Array: Here, we are going to learn how to insert/add elements to an array in Python programming language?
Submitted by IncludeHelp, on March 04, 2020

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

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

Example:

# 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

Ad: Are you a blogger? Join our Blogging forum.








Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.