Are list-comprehensions and functional functions faster than “for loops”?

In terms of performance in Python, is a list-comprehension, or functions like map(), filter() and reduce() faster than a for loop? Why, technically, they run in a C speed, while the for loop runs in the python virtual machine speed?. Suppose that in a game that I’m developing I need to draw complex and huge … Read more

Accessing class variables from a list comprehension in the class definition

How do you access other class variables from a list comprehension within the class definition? The following works in Python 2 but fails in Python 3: class Foo: x = 5 y = [x for i in range(1)] Python 3.2 gives the error: NameError: global name ‘x’ is not defined Trying Foo.x doesn’t work either. … Read more

Is it possible to use ‘else’ in a list comprehension? [duplicate]

This question already has answers here: if/else in a list comprehension (12 answers) Closed 3 years ago. Here is the code I was trying to turn into a list comprehension: table=”” for index in xrange(256): if index in ords_to_keep: table += chr(index) else: table += replace_with Is there a way to add the else statement … Read more

How to unzip a list of tuples into individual lists? [duplicate]

This question already has answers here: Closed 9 years ago. Possible Duplicate: A Transpose/Unzip Function in Python I have a list of tuples, where I want to unzip this list into two independent lists. I’m looking for some standardized operation in Python. >>> l = [(1,2), (3,4), (8,9)] >>> f_xxx (l) [ [1, 3, 8], … Read more

Python’s most efficient way to choose longest string in list?

I have a list of variable length and am trying to find a way to test if the list item currently being evaluated is the longest string contained in the list. And I am using Python 2.6.1 For example: mylist = [‘abc’,’abcdef’,’abcd’] for each in mylist: if condition1: do_something() elif ___________________: #else if each is … Read more

List comprehension on a nested list?

I have this nested list: l = [[’40’, ’20’, ’10’, ’30’], [’20’, ’20’, ’20’, ’20’, ’20’, ’30’, ’20’], [’30’, ’20’, ’30’, ’50’, ’10’, ’30’, ’20’, ’20’, ’20’], [‘100’, ‘100’], [‘100’, ‘100’, ‘100’, ‘100’, ‘100’], [‘100’, ‘100’, ‘100’, ‘100’]] Now, what I want to do is convert each element in a list to float. My solution … Read more