Comprehension Expressions

A place where you can post Python-related tutorials you made yourself, or links to tutorials made by others.

Comprehension Expressions

Postby micseydel » Fri Feb 22, 2013 1:40 am

Last edited by micseydel on Fri Feb 22, 2013 3:19 am, edited 1 time in total.
User avatar
micseydel
 
Posts: 3000
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: Comprehension Expressions

Postby Mekire » Fri Feb 22, 2013 2:28 am

Question: I'm incredibly lazy. Can I print with a list comprehension?

Answer: Well yes you can Mr. Lazy-Guy.

In Python 3 print is a function so this is extremely simple:
Code: Select all
[print("So lazy!! "*i) for i in range(5)]

In Python 2.x this takes a little more work because print is a statement:
Code: Select all
from __future__ import print_function
[print("So lazy!! "*i) for i in xrange(5)]

The output of both will be:
Code: Select all
So lazy!!
So lazy!! So lazy!!
So lazy!! So lazy!! So lazy!!
So lazy!! So lazy!! So lazy!! So lazy!!

Anyway. Stop being so lazy.

-Mek
(I personally love doing this, but as previously admitted, I love one-liners.
New Users, Read This
  • Use code tags when posting code.
  • Include any errors with your post (in code tags).
  • Describe your problem; not your chosen solution.
  • Make examples the minimum length to demonstrate your issue.
User avatar
Mekire
 
Posts: 1710
Joined: Thu Feb 07, 2013 11:33 pm
Location: Tucson, Arizona

Re: Comprehension Expressions

Postby micseydel » Fri Feb 22, 2013 3:14 am

If you want a one-liner for your terminal session, I don't know why you don't just write
Code: Select all
for i in range(5): print "lazy"

but as long as you don't put it into any real code, ever, that's fine.
Due to the reasons discussed here we will be moving to python-forum.io on October 1, 2016.

This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.
User avatar
micseydel
 
Posts: 3000
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA

Re: Comprehension Expressions

Postby Mekire » Fri Feb 22, 2013 3:45 am

Admittedly with the example I gave that can be done.
There would have to be an additional for or if statement within it to justify the one-liner.
Of course yes, it isn't really acceptable code, but I have always enjoyed the novelty that it can be done.

-Mek
New Users, Read This
  • Use code tags when posting code.
  • Include any errors with your post (in code tags).
  • Describe your problem; not your chosen solution.
  • Make examples the minimum length to demonstrate your issue.
User avatar
Mekire
 
Posts: 1710
Joined: Thu Feb 07, 2013 11:33 pm
Location: Tucson, Arizona


Return to Tutorials

Who is online

Users browsing this forum: No registered users and 5 guests