Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare and add items to an array in Python?

Tags:

python

arrays

I'm trying to add items to an array in python.

I run

array = {} 

Then, I try to add something to this array by doing:

array.append(valueToBeInserted) 

There doesn't seem to be a .append method for this. How do I add items to an array?

like image 304
AkshaiShah Avatar asked May 07 '12 18:05

AkshaiShah


People also ask

How do you add an item to an array?

JavaScript Array push() The push() method adds new items to the end of an array. The push() method changes the length of the array. The push() method returns the new length.

Can we add array in Python?

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 I add items to a NumPy array?

You can add a NumPy array element by using the append() method of the NumPy module. The values will be appended at the end of the array and a new ndarray will be returned with new and old values as shown above. The axis is an optional integer along which define how the array is going to be displayed.


1 Answers

{} represents an empty dictionary, not an array/list. For lists or arrays, you need [].

To initialize an empty list do this:

my_list = [] 

or

my_list = list() 

To add elements to the list, use append

my_list.append(12) 

To extend the list to include the elements from another list use extend

my_list.extend([1,2,3,4]) my_list --> [12,1,2,3,4] 

To remove an element from a list use remove

my_list.remove(2) 

Dictionaries represent a collection of key/value pairs also known as an associative array or a map.

To initialize an empty dictionary use {} or dict()

Dictionaries have keys and values

my_dict = {'key':'value', 'another_key' : 0} 

To extend a dictionary with the contents of another dictionary you may use the update method

my_dict.update({'third_key' : 1}) 

To remove a value from a dictionary

del my_dict['key'] 
like image 193
lukecampbell Avatar answered Oct 01 '22 17:10

lukecampbell