Python using enumerate inside list comprehension

Try this: [(i, j) for i, j in enumerate(mylist)] You need to put i,j inside a tuple for the list comprehension to work. Alternatively, given that enumerate() already returns a tuple, you can return it directly without unpacking it first: [pair for pair in enumerate(mylist)] Either way, the result that gets returned is as expected: … Read more

Are for-loops in pandas really bad? When should I care?

TLDR; No, for loops are not blanket “bad”, at least, not always. It is probably more accurate to say that some vectorized operations are slower than iterating, versus saying that iteration is faster than some vectorized operations. Knowing when and why is key to getting the most performance out of your code. In a nutshell, … Read more

How to remove multiple items from a list in just one statement?

In Python, creating a new object e.g. with a list comprehension is often better than modifying an existing one: item_list = [‘item’, 5, ‘foo’, 3.14, True] item_list = [e for e in item_list if e not in (‘item’, 5)] … which is equivalent to: item_list = [‘item’, 5, ‘foo’, 3.14, True] new_list = [] for … Read more

How to handle exceptions in a list comprehensions?

I realize this question is quite old, but you can also create a general function to make this kind of thing easier: def catch(func, handle=lambda e : e, *args, **kwargs): try: return func(*args, **kwargs) except Exception as e: return handle(e) Then, in your comprehension: eggs = (1,3,0,3,2) [catch(lambda : 1/egg) for egg in eggs] [1, … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)