Reputation: 5939
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 an .append
method for this. How do I add items to an array?
Upvotes: 494
Views: 1309223
Reputation: 23051
extend()
by a singletonIt's purely academic but extend()
method can be used to append a value to a list as well. Simply wrap the value in a tuple/list and extend the list by it.
lst = []
value = 1
lst.extend((value,)) # <--- (value,) is a singleton tuple
As it happens, it's faster than iadd
(+= [1]
)-ing a singleton list. In fact, it performs the same as list.append
. See the results here. Also, since it's faster to build a tuple than a list, extending by a singleton tuple is faster than by a singleton list.
import timeit
t1 = min(timeit.repeat("lst.append(1)", "lst = []")) # 0.058306435006670654
t2 = min(timeit.repeat("lst += [1]", "lst = []")) # 0.08136546600144356
t3 = min(timeit.repeat("lst.extend((1,))", "lst = []")) # 0.05731289298273623
t4 = min(timeit.repeat("lst.extend([1])", "lst = []")) # 0.1094264310086146
However, if the list is not a singleton, iadd
(+=
) is very competitive in terms of performance compared to list.extend
as the following experiment shows.
t5 = min(timeit.repeat("lst += items", "lst = []; items=[1, 2]")) # 0.033552975044585764
t6 = min(timeit.repeat("lst.extend(items)", "lst = []; items=[1, 2]")) # 0.060612224973738194
array
moduleThe standard library also has the array
module, which is a wrapper over C arrays. Like C arrays, array.array
objects hold only a single type (which has to be specified at object creation time by using a type code), whereas Python list
objects can hold anything. It also defines append
/extend
/remove
etc. to manipulate the data. It's useful if there is a need to interface with C arrays.
import array
arr = array.array('f') # initialize a float array
arr.append(1) # append 1.0 to it (because its type is float)
arr.extend([2, 3]) # extend it by multiple values
lst = arr.tolist() # convert to list
arr # array('f', [1.0, 2.0, 3.0])
lst # [1.0, 2.0, 3.0]
# `arr` only accepts floats; `lst` doesn't have that restriction
lst.append('string') # <---- OK
arr.append('string') # <---- TypeError: must be real number, not str
The main advantage of array.array
objects over list
s is memory-efficiency. As you can see from the example below, arr
consumes roughly 10 times less memory than lst
.
from pympler.asizeof import asizeof
lst = list(range(1_000_000))
arr = array.array('I', lst)
asizeof(lst) # 40000048
asizeof(arr) # 4000064
In special cases, working with array.array
objects may be faster than working with lists. There's an anecdote on the Python website that gives one such example. It's about converting a list of integers into strings. A modern version could look like below (converting to array.array
is still faster than str.join
).
setup = "import array; lst=list(range(97,123))"
t8 = min(timeit.repeat("''.join(map(chr, lst))", setup)) # 2.106592966010794
t9 = min(timeit.repeat("array.array('B', lst).tobytes().decode()", setup)) # 1.2953468860359862
Upvotes: 1
Reputation: 8125
Isn't it a good idea to learn how to create an array in the most performant way?
It's really simple to create and insert an values into an array:
my_array = ["B","C","D","E","F"]
But, now we have two ways to insert one more value into this array:
Slow mode:
my_array.insert(0,"A")
- moves all values to the right when entering an "A" in the zero position:
"A" --> "B","C","D","E","F"
Fast mode:
my_array.append("A")
Adds the value "A" to the last position of the array, without touching the other positions:
"B","C","D","E","F", "A"
If you need to display the sorted data, do so later when necessary. Use the way that is most useful to you, but it is interesting to understand the performance of each method.
Upvotes: 0
Reputation: 181280
If you do it this way:
array = {}
you are making a dictionary, not an array.
If you need an array (which is called a list in python ) you declare it like this:
array = []
Then you can add items like this:
array.append('a')
Upvotes: 66
Reputation: 93
You can also do:
array = numpy.append(array, value)
Note that the numpy.append()
method returns a new object, so if you want to modify your initial array, you have to write: array = ...
Upvotes: 2
Reputation: 16056
Just for sake of completion, you can also do this:
array = []
array += [valueToBeInserted]
If it's a list of strings, this will also work:
array += 'string'
Upvotes: 16
Reputation: 21
I believe you are all wrong. you need to do:
array = array[]
in order to define it, and then:
array.append ["hello"]
to add to it.
Upvotes: -3
Reputation: 25094
In some languages like JAVA you define an array using curly braces as following but in python it has a different meaning:
Java:
int[] myIntArray = {1,2,3};
String[] myStringArray = {"a","b","c"};
However, in Python, curly braces are used to define dictionaries, which needs a key:value
assignment as {'a':1, 'b':2}
To actually define an array (which is actually called list in python) you can do:
Python:
mylist = [1,2,3]
or other examples like:
mylist = list()
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist)
>>> [1,2,3]
Upvotes: 3
Reputation: 15256
{}
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']
Upvotes: 862
Reputation: 2196
Arrays (called list
in python) use the []
notation. {}
is for dict
(also called hash tables, associated arrays, etc in other languages) so you won't have 'append' for a dict.
If you actually want an array (list), use:
array = []
array.append(valueToBeInserted)
Upvotes: 19