AkshaiShah AkshaiShah - 4 months ago 26
Python Question

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

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:


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

Answer Source

{} represents an empty dictionary

What you are looking for for a list is [] To initialize an empty list do something like

my_list = []


my_list = list()

To add elements to the standard python list you use append


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

--> [12,1,2,3,4]

To remove an element from a list use remove


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']