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?
{} 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']
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')
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)
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'
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]
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 = ...
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.
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.
Related
I have a python list, like so:
list = [('array_1','array_2'),('array_1','array_3'),('array_2','array_3')]
The pairs in the list above are actually named numpy arrays, so I want to remove the quotes around each array name so that I'm left with:
list = [(array_1, array_2), (array_1, array_3), (array_2, array_3)]
How do I go about doing this?
Now you lst will contain actual NumPy arrays instead of just strings.
lst = [("array_1", "array_2"), ("array_1", "array_3"), ("array_2", "array_3")]
lst = [(globals()[i], globals()[j]) for i, j in lst]
This will output the numpy array (like array_1):
# str will be like : 'array_1'
globals()[str]
or
eval(str)
Note :
But I recommend to create a dictionary with keys as the strings and values as the corresponding arrays instead of eval and globals()
like this:
dict_ = {'array_1': array_1, 'array_2': array_2, 'array_3': array_3}
And use this dictionary wherever you want to access the variable
I want to create dynamic arrays inside a dynamic array because I dont know how many lists it will take to get the actual result. So using python 2.x when I write
Arrays = [[]]
does this mean that there is only one dynamic array inside an array or it can mean to be more than one when call for it in for loop like arrays[i]?
If it's not the case do you know a different method?
You can just define
Arrays = []
It is enough to hold your dynamic array.
AnotherArray1 = []
AnotherArray2 = []
Arrays.append(AnotherArray1)
Arrays.append(AnotherArray2)
print Arrays
Hope this solves your problem!
Consider using
Arrays = []
and later, when you are assigning your results use
Arrays.append([result])
This is assuming that your result comes in slices, but not as an array. No matter your actual return value layout, a variation of the above .append() should do the trick, as it allows you to dynamically extend your array. If your result comes as an array, it would simply be
Arrays.append(result)
and so on
If your array is going to be sparse, that is a lot of empty elements, you can consider to have a dict with coordinates as keys instead of nested lists:
grid = {}
grid[(x, y)] = value
print(grid)
output: {(x, y): value}
I am initializing my list object using following code.
list = [
func1(centroids[0],value),
func1(centroids[1],value),
....,
func1(centroids[n],value)]
I am trying to do it a more elegant way using some inline iteration. Following is the pseudo code of one possible way.
list = [value for value in func1(centroids[n],value)]
I am not clear how to call func1 in an iterative way. Can you suggest a possible implementation?
For a list of objects, Python knows how to iterate over it directly so you can eliminate the index shown in most of the other answers,
res = [func1(c, value) for c in centroids]
That's all there is to it.
A simple list comprehension consists of the "template" list element, followed by the iterator needed to step through the desired values.
my_list = [func1(centroids[0],value)
for n in range(n+1)]
Use this code:
list = [func1(centroids[x], value) for x in range(n)]
This is called a list comprehension. Put the values that you want the list to contain up front, then followed by the for loop. You can use the iterating variable of the for loop with the value. In this code, you set up n number(s) of variable(s) from the function call func1(centroids[x], value). If the variable n equals to, let's say, 4, list = [func1(centroids[0], value), func1(centroids[0], value), func1(centroids[0], value), func1(centroids[0], value)] would be equal to the code above
I have a list of xref values
internal_customer = {'01':'11', '03':'33', '05':'55', '07':'77', '08':'88', '06':'66', '09':'22', '11':'18', '12':'19'}
that I would like to use to sub a value in a tuple:
('03', 'S/N A1631703')
So my resulting tuple would be
('33', 'S/N A1631703')
Can someone point me in the direction of the tools I could use to accomplish this?
Unpack and access the dict using the first element, presuming you have an list of tuples:
internal_customer = {'01':'11', '03':'33', '05':'55', '07':'77', '08':'88', '06':'66', '09':'22', '11':'18', '12':'19'}
lst = [('03', 'S/N A1631703'),('05', 'S/N A1631703')]
lst[:] = ((internal_customer[a], b) for a,b in t)
print(t)
tuples are immutable so there is no notion of mutating, you have to create a new tuple comprising of the new value from the dict and the existing second element. The lst[:] syntax at least allows you to modify the original list. You can of course just reassign the name or create a completely new list if you want to maintain the original.
I have tried to define a function to create a two-tiered dictionary, so it should produce the format
dict = {tier1:{tier2:value}}.
The code is:
def two_tier_dict_init(tier1,tier2,value):
dict_name = {}
for t1 in tier1:
dict_name[t1] = {}
for t2 in tier2:
dict_name[t1][t2] = value
return dict_name
So the following example...
tier1 = ["foo","bar"]
tier2 = ["x","y"]
value = []
foobar_dict = two_tier_dict_init(tier1,tier2,value)
on the face of it produces what I want:
foobar_dict = {'foo':{'x': [],'y':[]},
'bar':{'x': [],'y':[]}} }
However, when appending any value like
foobar_dict["foo"]["x"].append("thing")
All values get appended so the result is:
foobar_dict = {'foo':{'x': ["thing"],'y':["thing"]},
'bar':{'x': ["thing"],'y':["thing"]}}
At first I assumed that due to the way my definition builds the dictionary that all values are pointing to the same space in memory, but I could not figure out why this should be the case. I then discovered that if I change the value from an empty list to an integer, when I do the following,
foobar_dict["foo"]["x"] +=1
only the desired value is changed.
I must therefore conclude that it is something to do with the list.append method, but I can not figure it out. What is the explanation?
N.B. I require this function for building large dictionaries of dictionaries where each tier has hundreds of elements. I have also used the same method to build a three-tiered version with the same issue occurring.
You only passed in one list object, and your second-tier dictionary only stored references to that one object.
If you need to store distinct lists, you need to create a new list for each entry. You could use a factory function for that:
def two_tier_dict_init(tier1, tier2, value_factory):
dict_name = {}
for t1 in tier1:
dict_name[t1] = {}
for t2 in tier2:
dict_name[t1][t2] = value_factory()
return dict_name
Then use:
two_tier_dict_init(tier1, tier2, list)
to have it create empty lists. You can use any callable for the value factory here, including a lambda if you want to store an immutable object like a string or an integer:
two_tier_dict_init(tier1, tier2, lambda: "I am shared but immutable")
You could use a dict comprehension to simplify your function:
def two_tier_dict_init(tier1, tier2, value_factory):
return {t1: {t2: value_factory() for t2 in tier2} for t1 in tier1}
It happens because you are filling all second-tier dicts with the same list that you passed as value, and all entries are pointing to the same list object.
One solution is to copy the list at each attribution:
dict_name[t1][t2] = value[:]
This only works if you are sure that value is always a list.
Another, more generic solution, that works with any object, including nested lists and dictionaries, is deep copying:
dict_name[t1][t2] = copy.deepcopy(value)
If you fill the dicts with an immutable object like a number or string, internally all entries would refer to the same object as well, but the undesirable effect would not happen because numbers and strings are immutable.
All the values refer to the same list object. When you call append() on that list object, all of the dictionary values appear to change at the same time.
To create a copy of the list change
dict_name[t1][t2] = value
to
dict_name[t1][t2] = value[:]
or to
dict_name[t1][t2] = copy.deepcopy(value)
The former will make a shallow (i.e. one-level) copy, and the latter will do a deep copy.
The reason this appears to work with ints is because they are immutable, and augmented assignments (+= and friends) do a name rebind just like ordinary assignment statements (it just might be back to the same object). When you do this:
foobar_dict["foo"]["x"] +=1
you end up replacing the old int object with a different one. ints have no capability to change value in-place, so the addition builds (or, possibly finds, since CPython interns certain ints) a different int with the new value.
So even if foobar_dict["foo"]["x"] and foobar_dict["foo"]["y"] started out with the same int (and they did), adding to one of them makes them now contain different ints.
You can see this difference if you try it out with simpler variables:
>>> a = b = 1
>>> a is b
True
>>> a += 1
>>> a
2
>>> b
1
On the other hand, list is mutable, and calling append doesn't do any rebinding. So, as you suspected, if foobar_dict["foo"]["x"] and foobar_dict["foo"]["y"] are the same list (and they are - check this with is), and you append to it, they are still the same list.