Array in Python

Array in Python

Array in Python

Array in Python

Python does not have in-built array. However, in C/C++ and Java you have learnt array and have expectation that it would be in Python. Further, array also a very important data structure and needs in several applications and algorithm implementations.
In Python, there are two ways to create an array.
In this post, I will demonstrate how to create an integer type array and input will be from user.

1- Modify a List

In Python, a list can have string, float and integer, to convert a list into an array you need to restrict the type of input.
>>>a=[] >>>len=int(input(‘ln’))
>>>for i in range(0,len):
>>>…x=int(input(‘Enter integers otherwise it will through error’))
>>>…a.append(x)

In the above program.
I have created an empty list a=[] Length of array from user len=int(input(‘ln’))
In for loop, I take input which is restricted to integer x=int(input())
And then a.append(x) appendĀ  value in x to array a.

2- Using Package array

The second method is to use array package, in which array() constructor is used to create an array. Constructor array() takes two arguments the first
one is type of array and another is list.
>>>import array as arr
>>>a = arr.array(‘i’, [])
>>>len=int(input(‘ln’))
>>>for i in range(0,len):
>>>…x=int(input(‘Enter integers otherwise it will through error’))
>>>…a.append(x)

In the above program, an empty array a, which is created using statement a = arr.array(‘i’, [])
Length of array from user len=int(input(‘ln’))
In for loop, I take input which is restricted to integer x=int(input())
And then a.append(x) appendĀ  value in x to array a.

Share to Your Friend
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Be the first to comment on "Array in Python"

Leave a comment

Your email address will not be published.


*