How to declare and add items to an array in Python? - 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:
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

Is there a better way to add entries from lists to a dictionary?

As I was studying Python, I came across this task:
Imagine Python did not have built-in support for sets. Show how we
could use dictionaries to represent sets. Write the four set
operations | - ^ & for this new representation of sets.
Below you can see the answer:
First, for the ‘or’ operation, we add entries to the new dictionary
from both input lists:
l1 = [1,2,3,4,5]
l2 = [4,5,6,7,8]
def t_or(l1,l2):
result = {}
for x in l1: result[x] = 0
for x in l2: result[x] = 0
print(result)
So, I'm wondering why have the author used such a strange method to add entries result[x] = 0? Isn't there a better way to do it, maybe using alternatives methods like .add, .insert, etc?
result[key] = value is the way to assign a new pair key:value in a Python dictionary. You don't have to create the entry key first on a Dictionary. If you come from Java, for example, the syntaxis is like:
Map<String, String> result = new HashMap<int, int>();
result.put(1, 0);
As you can see, on Java you are not declaring the key too, the same happens on a lot of languages and that is because of how a dictionary key works.
When you want to retrieve an element from a dictionary, you have to be sure that the key already exists in the dictionary, otherwise it will throw an exception.
The .add or .insert that you have in mind in Python is .append and it is used to add a new element to a list:
my_list = []
my_list.append(0)
So no, there is no a better way or a different way to assign new key:value pairs on a Python dictionary.

Navigating nested dictionary

I'm trying to wrap my head around how to navigate a series of dictionaries nested in a list.
For example: mydict = {'first':[{'second':2, 'third':3}, {'fourth':4}]}
When I type mydict.get('first'), I get the whole list.
I can't use indexing to get each individual dictionaries in the list (i.e. mydict.get(['first'][0] returns the whole list, and mydict.get(['first'][1]) returns an IndexError).
mydict.get(['first'][0]['second']) andmydict.get(['first']['second']) return TypeErrors.
So, if I wanted to call 'second' or 'fourth' or assign their values to variables, how would I do it?
For second:
mydict['first'][0]['second]
['first'] returns the array
[0] returns the first object of the array
['second'] gets the 'second' object
Perhaps try reshaping your data to something more convenient?
In your example, mydict isn't a series of dictionaries nested in a list. It is a dictionary that contains lists that, in turn, contain dictionaries.
So assuming you don't know which inner dictionary will contain the key you're looking for, you'd have to iterate over all the entries in the parent dictionary to find it. Something like:
desiredKey = 'second'
for listOfDict in mydict.values():
for childDict in listOfDict:
if desiredKey in childDict:
print(childDict[desiredKey])
This will only work if the key you're looking for is always in the inner most dictionaries.

How to get listcomprehension result as unpacked list

I have a function (in the example: some_function()) that returns a set. I got a data structure of some elements (in the example arr) and need to map the elements to the function and I want to get back a set of all elements. Not a set of sets but a set of all the elements that are in the sets. I know that some_function() only returns one dimensional sets.
I tried to use map but didn't quite get it to work, I got it to work with list comprehensions but I don't really like my solution.
Is it possible to not create a list and then unpack it?
Or can I somehow convert what I get from my map approach without much work?
Example:
arr = [1, 2, 3]
# I want something like this
set.union(some_function(1), some_function(2), some_function(3))
# where some_function returns a set
# this is my current solution
set.union(*[some_function(el) for el in arr]))
# approach with map, but I couldn't convert it back to a set
map(some_function, arr)
You can use a generator expression instead of a list comprehension so that you don't have to create a temporary list first:
set.union(*(some_function(el) for el in arr)))
or, using map:
set.union(*map(some_function, arr))
I think your current solution is fine. If you want to avoid creating a list, you may try:
set.union(*(some_function(el) for el in arr)))
In Python, sometimes you just have to not be fancy.
result = set()
for el in arr:
result.update(some_function(el))
This approach doesn’t create a list of the return values and so doesn’t hold onto sets longer than necessary. You can wrap it in a function for cleanliness.

Sorting out unique elements from a list to a set

I was writing a function to save unique values returned by a list "list_accepted_car" to a set "unique_accepted_ant". list_car_id is list with the value ['12','18','3','7']. When i run the code i am getting error , "unhashable list ". Can anyone suggest me what is the error?
list_accepted_car = [] #set to store the value list_accepted_car
unique_accepted_car = set() #set to store the value unique_accepted_car
num_accepted = 2 #predifined value for the number of cars allowed to enter
def DoIOpenTheDoor(list_car_id): #list_ant_id is a list of cars allowed to enter
if len(list_accepted_car) < num_accepted:
if len(list_car_id) > 0:
list_accepted_car.append(list_car_id[0:min(len(list_car_id),num_accepted-len(list_accepted_car))])
unique_accepted_list = set(list_accepted_car)
print unique_accepted_list
return list_accepted_car
Under the assumption that list_car_id looks like: [1,2,3,4,5].
You add in list_accepted_car a sublist of list_car_id, so list_accepted_car will look like [[1,2]] i.e. a list of a list.
Then you should change
unique_accepted_list = set(list_accepted_car)
to
unique_accepted_list = set([x for y in list_accepted_car for x in y])
which will extract each element of the sublist and provide a flatten list. (There exists other options to flatten a list of list)
You are saving a list of lists, which can't be converted to a set. You have to flatten it first. There are many examples of how to do it (I'll supply one using itertools.chain which I prefer to python's nested comprehension).
Also, as a side note, I'd make this line more readable by separating to several lines:
list_accepted_car.append(list_car_id[0:min(len(list_car_id),num_accepted-len(list_accepted_car))])
You can do:
from itertools import chain
# code ...
unique_accepted_list = set(chain.from_iterable(list_accepted_car))
The best option would be to not use a list at all here, and use a set from the start.
Lists are not hashable objects, and only hashable objects can be members of sets. So, you can't have a set of lists. This instruction:
list_accepted_car.append(list_car_id[0:min(len(list_car_id),num_accepted-len(list_accepted_car))])
appends a slice of list_car_id to list_accepted_car, and a slice of a list is a list. So in effect list_accepted_car becomes a list of lists, and that's why converting it to a set:
unique_accepted_list = set(list_accepted_car)
fails. Maybe what you wanted is extend rather than append? I can't say, because I don't know what you wanted to achieve.

Unable to modify the elements of dict in python

I have defined a function called modify which modifies given string. I have a dict called elements which have some strings stored in them. However, I am unable to modify those strings stored in the dict.
x = "abc"
x = modify(x)
This works but when I do;
for element in elements:
element = modify(element)
This does not work. Any idea why? I'm fairly new to python.
You cannot modify the elements of a dict whilst iterating through them.
You'd need to use something like this:
for key in elements:
elements[key] = modify(elements[key])
If you need to apply a function to each member of a dictionary, consider using a dict comprehension:
elements = {k: modify(v) for k, v in elements.items()}
If you are using python 2.7 use elements.iteritems() instead of elements.items().

Categories