0 votes
1 view
in Python by (33.1k points)

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?

2 Answers

0 votes
by (16.8k points)

Basically, {} does not represents an array or a list, it is for defining an empty dictionary. 

If you want to define arrays or lists, you'd need [].

In order to initialize an empty list, try this:

my_list = []

or try this,

my_list = list()

Adding elements in the list, use append:

my_list.append(12)

For extending the list for including the elements from other list, try extend:

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

my_list

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

use remove to remove an elements from your list:

my_list.remove(2)

To initialize the empty dictionary, try dict() or {}

Dictionaries have keys and values like: 

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

If you want to extend the dictionary with the contents and another dictionary, then you can use the update command for this method:

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

For removing a value from the dictionary:

del my_dict['key']

0 votes
by (107k points)
edited by

You can use append() function to add an item to an array in Python see the code below:-

array = [] array.append(valueToBeInserted)

To know more about this you can have a look at the following video tutorial:-

Related questions

0 votes
1 answer
asked Oct 11, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
asked Jul 8, 2019 in Python by Sammy (47.8k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...