[Tutor] List Comprehension question
rabidpoobear at gmail.com
Tue Feb 9 00:30:12 CET 2010
On Mon, Feb 8, 2010 at 4:15 PM, <internets at shaneferguson.com> wrote:
> I've been trying to work my way through some 'beginner projects' I found
> around the web, one of them involves generating some random numbers. I
> decided to use a list of lists, and I'm wondering if this is a valid
> comprehension...IDLE doesn't seem to mind, but maybe I lack the experience
> to know better:
> numbers = [[random.randint(1, 10) for x in range(5)] for y in range(5)]
> I'm using Python 3.1. If this is valid, is there a shorter version or
> better way?
If Python executes it without throwing exceptions that means it's
syntactically valid. Are you asking if it's semantically valid? Well, that
depends what you're trying to do. Are you trying to make a 5x5 matrix of
random numbers chosen from [1,2,3,4,5,6,7,8,9,10]? In that case I'd say it
does what you want. most people opt to use randrange rather than randint
though as it makes more sense when related to other range functions.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor