Posts

Showing posts from May, 2012

Python | Nested List Comprehension

List Comprehension is a beautiful feature of Python. But most of the Python beginners (like me) get confused when it comes to nested list comprehension. So I thought to write few lines of Python code that might help you to understand it better. Can you figure out the output of the following statement? [(x, y) for x in range(1, 5) for y in range(0, x)] Here is the output: [(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2), (4, 0), (4, 1), (4, 2), (4, 3)] If you could figure it out correctly, you don't need to read the rest of the post. Now, look at the following code >>> for x in range(1, 5): ...     for y in range(0, x): ...         print x, y ... 1 0 2 0 2 1 3 0 3 1 3 2 4 0 4 1 4 2 4 3 >>> This is actually same as [(x, y) for x in range(1, 5) for y in range(0, x)] Now think about it, experiment with your own ideas and things will be clear. :)

UnicodeDecodeError in CSV writer in Python

I faced another error with UnicodeWriter class. Now it's UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 21: ordinal not in range(128) . More details: Traceback (most recent call last):   File "cpx_parser.py", line 284, in     main()   File "cpx_parser.py", line 278, in main     writer.writerow(csv_li)   File "cpx_parser.py", line 29, in writerow     self.writer.writerow([s.encode("utf-8") for s in row]) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 21: ordinal not in range(128) So, I had to decode s using utf-8, then convert it into unicode. And that solved the problem. Here is what I did: self.writer.writerow([unicode(s.decode("utf-8")).encode("utf-8") for s in row]) To know more about unicode, you can check this link .