# Python Gems

Page 1 of 1

## 5 Replies - 12436 Views - Last Post: 13 June 2014 - 05:53 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=286022&amp;s=29adbd110b00cac674e9eaad07d926aa&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 atraub

• Pythoneer

Reputation: 828
• Posts: 2,235
• Joined: 23-December 08

# Python Gems

Posted 16 July 2012 - 10:17 PM

POPULAR

Python has some awesome gems! Today, I'd like to share a few of my favorites with you.

List Comprehensions
There's already a good tutorial that goes into depth regarding list comprehensions, so I won't spend much time on this topic. But I simply love list comprehensions. You can quickly and easily generate some really cool stuff, here's a few examples that go a little further than the tutorial
```x = [i for i in range(100)] #list holding 0-99
y = [i for i in range(0,100,3)] #list holding values 0 - 99 counting by 3's
z = [i for i in range(0,100,3) if i%2 == 1] #list holding ODD values 0 - 99 counting by 3's

```

Generators
Anyone who's looked at the Python snippets section lately knows that I love generators! Generators typically allow you to create a series of values without being forced to store all the values at one time. A simple version might be this:
```def firstTen():
for i in range(10):
yield i

```

This function "yields" the values 0 through 9. However, only one of these values are stored in memory at a given time. Here's an example of how this function would be used:
```>>> x = firstTen()
>>> print(next(x))
0
>>> print(next(x))
1
>>>for i in range(5):
print(next(x))

2
3
4
5
6

```

As you can see, we get the next value of the generator by using the next function. This example is cute, but it doesn't showcase the true power of generators!

Here's a slightly better example:
```x = (i for i in range(100000000))

```

This creates a generator that will cycle through 100,000,000 numbers, but only 1 given value will be held in memory at a given time. Imagine how much less memory that would take up than having a list holding 100,000,000 numbers! However, I think the best is yet to come.
These generators are far better examples: Digit Product Sequence, Look and Say Sequence, and ever the crowd pleaser, fibonacci. These snippets create generators of unlimited sets. You can continue making larger and larger numbers until your pc has trouble keeping up.

Also, pretty cool, you can use generators in combination with list comprehensions! here's an example using the fibonacci generator:
```x = fibonacciGenerator()
y = [next(x) for i in range(100)]

```

Using a generator that already existed, I used a list comprehension to get the first 100 Fibonacci values. Very cool.

Collections
Yeah, python's lists are pretty awesome, but I came across a particularly cool gem the other night. I remember in a previous post, one guy was trying to construct a dictionary from a list. for each unique value in the list, the dictionary would have a key. The value associated with that key would be the number of times that particular value occurred in the list. Little did he know that this could be accomplished with ease using a built in structure, the counter dictionary!
```>>> from collections import Counter
>>> x = [1,2,2,5,7,3,5,7,8,45,7,8,4,5,8,4,]
>>> y = Counter(x)
>>> print(y)
Counter({5: 3, 7: 3, 8: 3, 2: 2, 4: 2, 1: 1, 3: 1, 45: 1})

```

I bet there are a lot of other cool things in that module, but I haven't taken the time to really look at it.

Join
Here's another short and sweet one. Using string.join() one is able to quickly turn a list into a nicely formatted string. Here's a few quick examples that are hopefully self explanatory:
```>>> from random import randint
>>> x = [str(randint(0,9)) for i in range(20)]
>>> print(x)
['7', '7', '1', '9', '0', '9', '3', '4', '0', '1', '0', '3', '8', '3', '1', '7', '6', '3', '4', '6']

>>> ''.join(x)
'77190934010383176346'

>>> ', '.join(x)
'7, 7, 1, 9, 0, 9, 3, 4, 0, 1, 0, 3, 8, 3, 1, 7, 6, 3, 4, 6'

>>> ','.join(x)
'7,7,1,9,0,9,3,4,0,1,0,3,8,3,1,7,6,3,4,6'

>>> "("  +  ')-('.join(x)  +  ")"
'(7)-(7)-(1)-(9)-(0)-(9)-(3)-(4)-(0)-(1)-(0)-(3)-(8)-(3)-(1)-(7)-(6)-(3)-(4)-(6)'

>>> '->'.join(x)
'7->7->1->9->0->9->3->4->0->1->0->3->8->3->1->7->6->3->4->6'#reminds me of a linked list, don't you agree?

```

So, those are my top 4 favorite Python gems. What are your favorites?

This post has been edited by atraub: 18 July 2012 - 07:17 AM

Is This A Good Question/Topic? 7

## Replies To: Python Gems

### #2 atraub

• Pythoneer

Reputation: 828
• Posts: 2,235
• Joined: 23-December 08

## Re: Python Gems

Posted 22 July 2012 - 08:19 PM

List Comprehensions + Join for 2D list processing
Ok this one's pretty cool:
```x = [
[1,2,3,],
[4,5,6,],
[7,8,9,],
]

```

I can use a combination of list comprehensions and join methods in order to print the list out in a well formatted way.
```>>> '\n'.join([' '.join([str(value) for value in row]) for row in x])
1 2 3
4 5 6
7 8 9
>>> print('\n'.join([','.join([str(value) for value in row]) for row in x]))
1,2,3
4,5,6
7,8,9
>>> print("[\n ["+']\n ['.join([','.join([str(value) for value in row]) for row in x]) + "]\n]")
[
[1,2,3]
[4,5,6]
[7,8,9]
]

```

This post has been edited by atraub: 22 July 2012 - 08:37 PM

### #3 xTorvos

• D.I.C Regular

Reputation: 61
• Posts: 271
• Joined: 23-October 09

## Re: Python Gems

Posted 24 July 2012 - 12:43 AM

I think reversing a string/list is pretty fun:

```>>> s = "Hello world!"
>>> s[::-1]
!dlrow olleH

```

This post has been edited by xTorvos: 24 July 2012 - 12:44 AM

### #4 atraub

• Pythoneer

Reputation: 828
• Posts: 2,235
• Joined: 23-December 08

## Re: Python Gems

Posted 12 September 2012 - 09:04 PM

Lately, I've found myself using the same string method a lot, it's really come in handy for checking file extensions, here's an example:
```#string.endswith(extension)
filename.endswith(".py")
```

Reputation: 10
• Posts: 64
• Joined: 16-May 14

## Re: Python Gems

Posted 24 May 2014 - 11:43 PM

atraub, on 22 July 2012 - 08:19 PM, said:

List Comprehensions + Join for 2D list processing
Ok this one's pretty cool:
```x = [
[1,2,3,],
[4,5,6,],
[7,8,9,],
]

```

I can use a combination of list comprehensions and join methods in order to print the list out in a well formatted way.
```>>> '\n'.join([' '.join([str(value) for value in row]) for row in x])
1 2 3
4 5 6
7 8 9
>>> print('\n'.join([','.join([str(value) for value in row]) for row in x]))
1,2,3
4,5,6
7,8,9
>>> print("[\n ["+']\n ['.join([','.join([str(value) for value in row]) for row in x]) + "]\n]")
[
[1,2,3]
[4,5,6]
[7,8,9]
]

```

Well, python does have a module for that.

```import pprint
x = [
[1,2,3,],
[4,5,6,],
[7,8,9,],
]
pprint.pprint(x, width=12)

```

### #6 atraub

• Pythoneer

Reputation: 828
• Posts: 2,235
• Joined: 23-December 08

## Re: Python Gems

Posted 13 June 2014 - 05:53 AM

Shadowys, on 25 May 2014 - 01:43 AM, said:

atraub, on 22 July 2012 - 08:19 PM, said:

List Comprehensions + Join for 2D list processing
Ok this one's pretty cool:
```x = [
[1,2,3,],
[4,5,6,],
[7,8,9,],
]

```

I can use a combination of list comprehensions and join methods in order to print the list out in a well formatted way.
```>>> '\n'.join([' '.join([str(value) for value in row]) for row in x])
1 2 3
4 5 6
7 8 9
>>> print('\n'.join([','.join([str(value) for value in row]) for row in x]))
1,2,3
4,5,6
7,8,9
>>> print("[\n ["+']\n ['.join([','.join([str(value) for value in row]) for row in x]) + "]\n]")
[
[1,2,3]
[4,5,6]
[7,8,9]
]

```

Well, python does have a module for that.

```import pprint
x = [
[1,2,3,],
[4,5,6,],
[7,8,9,],
]
pprint.pprint(x, width=12)

```

who knew?