Python For Loop to List - python

I have a beginner Python question. I was wondering if it was possible to take the results of a for loop that came from a list and then turn it back into a list again. I've got code that looks something like this.
for a in mylist:
result = q.myfunction(a)
print q, a
I would like the results of this list to be something that I can use to create a table in my database. I am using Python 2.7 on Windows 7. I have looked through the documentation from python on for loops, and looked through questions on stack exchange, and I am still confused.

Sure.
Just printing things out obviously doesn't append them to a list. But calling the append method on a list does, as explained in the Lists section of the tutorial. For example:
mynewlist = []
for a in mylist:
result = q.myfunction(a)
print q, a
mynewlist.append(result)
If all you want to do is create a new list, no other side effects, a list comprehension makes it even simpler. This code:
mynewlist = [q.myfunction(a) for a in mylist]
… does the same as the above, but without the print.

If you're used to using for loops then you can do the following:
results = []
for a in mylist:
result = q.myfunction(a)
results.append(result)
However, the idiomatic way to do something like this in python is to use what's known as a list comprehension. List comprehensions are a way of producing new lists from the elements of others lists. For example, the following has exactly the same effect as the above for loop.
results = [q.myfunction(a) for a in mylist]

Is this what you want?
[q.myfunction(a) for a in mylist]
It's called a list comprehension.

Related

python: how to append multiple lists to one

I have a list that should contain all my other lists. Currently I append every list separately but that just looks pretty ugly..
looplist = [] # initiate an empty list that contains all date from the other lists
[...]
looplist.append(internallist1)
[...]
looplist.append(internallist10)
the internallists are all getting initialized and filled in a for loop
You can simply use + to merge them.
You may check for more info.
If you want to have list of lists, check this topic.
listOne.extend(anotherList)
this could help you: https://docs.python.org/3/tutorial/datastructures.html
you can also do listOne+=anotherList and this is less expensive, as it doesn`t involve a function call like extend
To answer what you are asking, Just initialize looplist with your 10 lists.
looplist = [internallist1,
internallist2,
internallist3] #Note: internallist3,] is also valid, python allows trailing comma. Nifty!
However, your 10 lists really shouldn't be separately named lists in the first place if this is your real use case. Just use looplist[0] through looplist[9] instead from the get go.
The zip method could work for you as you stated your output should:
look something like [ [list1], [list2], ... , [list n] ]
in your case the code would be similar to
looplist = list(zip(internallist1,[...], internallist10))

update value of element stored in 2 different lists [duplicate]

I am new to data structures in python and was wondering how do you simulate a thing like pointers in python so that multiple structures can refer and manage the same piece of data.
I have the following two structures
my_list = [1]
my_dictionary = {}
my_dictionary["hello"] = my_list[0]
and when I do the following I get True
id(my_dictionary["hello"]) == my_list[0]
However how can I force removal both from the dict and the list in one go?
If I do the following my_dictionary still has a reference to my_list[0] i.e. 1
del my_list[0]
is there a way to get rid of both of these elements in one go? What is the python way of doing linked structures like this?
It really depends on the point you're trying to solve by cross-referencing.
Suppose your intent is to be able to efficiently both locate an item by key, as well as to sequentially iterate by order. In this case, irrespective of the language, you probably would wish to avoid cross referencing a hash-table and an array data structures, as the updates are inherently linear. Conversely, cross referencing a hash-table and a list might make more sense.
For this, you can use something like llist:
d = {}
l = llist.dllist()
# insert 'foo' and obtain the link
lnk = l.append('foo')
# insert the link to the dictionary
d['foo'] = lnk
Conversely, suppose your intent is to be able to efficiently both locate an item by key, as well as to locate by index. Then you can use a dict and a list, and rebuild the list on each modification of the dict. There is no real reason for fancy cross-referencing.
Simply put, there is no way to easily link your two structures.
You could manipulate the object you point to so that it has some "deleted" state and would act as if it's deleted (while being in both containers).
However, if all you wanted was a list from a dict, use list(the_dict.values()).
You could make a class to achieve this, if all else fails. See https://docs.python.org/2/reference/datamodel.html#emulating-container-types for the details on what your class would have to have. Within the class, you would have your "duplicated effort," but if it's correctly implemented it wouldn't be error prone.
You can always do things like this:
Pointers in Python?
(a quick stackoverflow search shows some results)
But that is messing with more than just data structures.
Remember that Python manages memory for you (in most of the cases, pretty well), so you don't have to worry of cleaning after yourself.
i have tried the following peice of code and it works (changing in one DataStructure changes for the other).
does this help?
list1 = [1,2,3]
list2 = [4,5,6]
my_dictionary = {}
my_dictionary["a"] = list1
my_dictionary["b"] = list2
del list1[0]
print list1
print list2
print my_dictionary

Equating a list to the function of another list

At the moment, I have a piece of code with lots of lists equal to the function of another list, embedded in a loop in Python:
Power = [x,y,z]
Force = []
for i in range(len(Power)):
Force.append(((function(Power[i])-0.5))/slope)
I would like to simplify it down to:
Force = function(Power[i])-0.5))/slope)
but it doesn't work. It does however work when there's no function, just a simple relationship. Is this possible in Python?
You can use a list comprehension:
Force = [(function(x)-0.5)/slope for x in Power]
As far as I am aware the most concise / simplest way to do this is via list comprehension, in particular you can do something as follows:
Force = [(function(Power[i])-0.5)/slope for i in range(len(Power))]
Very similar to what you have already done earlier, but comes in a nice and simple one line expression.

How to create a function in Python that makes objects (i.e lists)

I couldn't find a guide that would help me out in this area. So I was hoping somebody could help me explain this kind of programming in Python. I am trying to write a code that goes something like this:
def Runner():
for G in range(someRange):
makeListObjectcalled 'ListNumber'+'G'
ListNumberg.append(G*500000 or whatever)
print ListNumberG
#so I would have a someRange amount of lists
#named 0,1,2,3...(up to someRange) I could look through
I think it can be done with classes (in fact I'm guessing thats what they're for...) but I'm not sure. Could someone lay me down some clarifications please?
It looks like what you really want is a list of lists.
def Runner():
Lists = []
for G in range(someRange):
Lists[G] = []
Lists[G].append(G*500000 or whatever)
print Lists[G]
#This way, you have Lists[0], Lists[1], ..., Lists[someRange]
You want to dynamically create variables of type lists that store an array of values.
An easier and better approach (than juggling unknown variable names) is to use a dictionary to keep your lists in, so you can look them up by name/key:
(pseudo code, don't have my Python interpreter with me)
# create a dictionary to store your ListNumberG's
dict_of_lists = {}
# down the line in your loop, add each generated list to the dict:
dict_of_lists['ListNumberG'] = ListNumberG
Later you can find a list by it's name/key via
print(dict_of_lists['ListNumberG'])
or loop through them
for idx in range(bestguess):
print(dict_of_lists['ListNumber%s' % (idx,)])

How can I create a list in Python?

http://diveintopython3.ep.io/native-datatypes.html
I've found that link but it seems to rely on the fact that I first have to hard create the list. How can I create a list in Python if it's empty at first. I'm coming from a C# background so this is kind of weird so far.
For example the .append() method is what I'm looking for, but it relies on the fact that the list first exists. Any suggestions?
You can create an empty list like this
L=list()
or
L=[]
As noted by others, you can create an empty list with the list literal operator [].
Its worth noting that you can initialise the list with values if you always need to start with a few values already in place:
a = 5
L = [42, -12, a]

Categories

Resources