
-----------------------------------
Aange10
Tue May 29, 2012 4:44 pm

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.


t2 for t1 in my_list for t2 in my_list2


Thanks ;)

-----------------------------------
Aange10
Tue May 29, 2012 9:14 pm

RE:Single line for loops
-----------------------------------
To make it easier, also, lets say


my_list = 

-----------------------------------
chrisbrown
Thu May 31, 2012 3:37 am

Re: Single line for loops
-----------------------------------
Are you missing some brackets? I don't recognize that syntax but  is a nested list comprehension.


How much do you know about list comprehensions? Do you know what this does? 

-----------------------------------
Aange10
Thu May 31, 2012 1:11 pm

RE:Single line for loops
-----------------------------------
There may be those brackets there.

And somewhat. I'm not sure what happens to 't' in 


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
Thu May 31, 2012 5:33 pm

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: 
def list_comp(a_list, f):
    newlist = where f is any function that can be applied to every element of a_list.

So for the same my_list you provided,  evaluates to the list: 
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) = 

-----------------------------------
Aange10
Thu May 31, 2012 9:32 pm

RE:Single line for loops
-----------------------------------
Thankyou for explaining that! I understand. It now xD. Very cool tool.

Thanks! + karma ;)
