Saturday snippet – simple example of Python list comprehensions


Here’s something I was trying to do in ICE (without using any Repeats).

Given an array like

a = [ 5, 2 ,3 ]

create an array like

b = [ 0, 0, 0, 0, 0, 1, 1, 2, 2, 2 ]

See the pattern? (a[0] is 5, so array b has five elements with value 0).

In Python, using list comprehension, you can do it like this:

a = [ 5, 2, 3 ]

print [ i for i in range( len(a) ) for j in range( a[i] )]

The list comprehension is the equivalent of:

for i in range( len(a) ):
	for j in range( a[i] ):
		print i

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s