Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an integer array in Python?

Tags:

python

arrays

It should not be so hard. I mean in C,

int a[10];  

is all you need. How to create an array of all zeros for a random size. I know the zeros() function in NumPy but there must be an easy way built-in, not another module.

like image 551
PythontoBeLoved Avatar asked Dec 07 '09 13:12

PythontoBeLoved


People also ask

How do you create an array of numbers in Python?

Creating a Array Array in Python can be created by importing array module. array(data_type, value_list) is used to create an array with data type and value list specified in its arguments.

How do you create an integer array?

To initialize or instantiate an array as we declare it, meaning we assign values as when we create the array, we can use the following shorthand syntax: int[] myArray = {13, 14, 15}; Or, you could generate a stream of values and assign it back to the array: int[] intArray = IntStream.

How do you initialize an int array in Python?

To initialize an array with the default value, we can use for loop and range() function in python language. Python range() function takes a number as an argument and returns a sequence of number starts from 0 and ends by a specific number, incremented by 1 every time.

How do I create an integer array in NumPy?

To convert numpy float to int array in Python, use the np. astype() function. The np. astype() function takes an array of float values and converts it into an integer array.


2 Answers

If you are not satisfied with lists (because they can contain anything and take up too much memory) you can use efficient array of integers:

import array array.array('i') 

See here

If you need to initialize it,

a = array.array('i',(0 for i in range(0,10))) 
like image 129
yu_sha Avatar answered Sep 19 '22 02:09

yu_sha


two ways:

x = [0] * 10 x = [0 for i in xrange(10)] 

Edit: replaced range by xrange to avoid creating another list.

Also: as many others have noted including Pi and Ben James, this creates a list, not a Python array. While a list is in many cases sufficient and easy enough, for performance critical uses (e.g. when duplicated in thousands of objects) you could look into python arrays. Look up the array module, as explained in the other answers in this thread.

like image 22
catchmeifyoutry Avatar answered Sep 22 '22 02:09

catchmeifyoutry