Single line for loops
Author |
Message |
Aange10

|
Posted: Tue May 29, 2012 4:44 pm Post subject: Single line for loops |
|
|
In some of my classes, the teacher is using a very odd syntax. I'm not quite sure what is happening, so I'm starting to get lost in my class. Could somebody explain how these for loops are iterating? It'd probably help a lot to explain it in a nested format. I think I'd get it if I saw it like I'm used to seeing it.
Python: |
t2 for t1 in my_list for t2 in my_list2
|
Thanks  |
|
|
|
|
 |
Sponsor Sponsor

|
|
 |
Aange10

|
Posted: Tue May 29, 2012 9:14 pm Post subject: RE:Single line for loops |
|
|
To make it easier, also, lets say
Python: |
my_list = [0,1,2]
my_list2 = [0,1,2,3]
|
|
|
|
|
|
 |
chrisbrown

|
Posted: Thu May 31, 2012 3:37 am Post subject: Re: Single line for loops |
|
|
Are you missing some brackets? I don't recognize that syntax but Python: | [ [t2 for t1 in my_list] for t2 in my_list2 ] | is a nested list comprehension.
How much do you know about list comprehensions? Do you know what this does? Python: | [t for t in my_list] |
|
|
|
|
|
 |
Aange10

|
Posted: Thu May 31, 2012 1:11 pm Post subject: RE:Single line for loops |
|
|
There may be those brackets there.
And somewhat. I'm not sure what happens to 't' in
Python: |
t for t in my_list
|
but i know that the 'for t in my_list' will just iterate through the list and store the elements value to t. |
|
|
|
|
 |
chrisbrown

|
Posted: Thu May 31, 2012 5:33 pm Post subject: Re: Single line for loops |
|
|
OK good stuff. You're right about t being the variable of iteration. But where a for loop simply evaluates the expression(s) within it, a list comprehension builds a new list by applying those expressions to each element as it iterates through the original list. You could encapsulate the same behaviour in a function: Python: |
def list_comp(a_list, f):
newlist = []
for t in a_list:
newlist.append( f(t) )
return newlist
# Test
[ f(t) for t in a_list ] == list_comp(a_list, f) # True
| where f is any function that can be applied to every element of a_list.
So for the same my_list you provided, Python: | [ f(t) for t in my_list ] | evaluates to the list: Python: | [ f(0), f(1), f(2) ] |
If f(t) = t like in my example, then the new list will be an element-wise copy of the original.
If f(t) = 0, you can produce a list of zeroes equal in length to the original.
If t(f) = [ t**0, t**1, t**2, t**3, (etc) ] you can produce a list of lists, where each element of the produced list is a list of powers for each element in the original list. (Wordy, I know...)
If f(t) = [ t for t2 in my_list2 ] ? |
|
|
|
|
 |
Aange10

|
Posted: Thu May 31, 2012 9:32 pm Post subject: RE:Single line for loops |
|
|
Thankyou for explaining that! I understand. It now xD. Very cool tool.
Thanks! + karma  |
|
|
|
|
 |
|
|