On this website, you will find tutorials for installing & managing software, lists of the best linux resources, and in depth guides to linux.

# 10 Python Tricks To Make Your Code Shorter

Robert Washbourne - a year ago - programming

These are mainly unique to python, so if you program in another language, these may be surprising. They certainly were for me when I got started with python.

## 1. Negative indexing

```
>>> a = [1,2,3]
>>> a[-2]
2
>>> a[-1]
3
```

## 2. List slices

```
>>> a = [1,2,3,4]
>>> a[2:4]
[3, 4]
```

## 3. Grouped naming

```
>>> a,b,c = [1,2,3]
>>> a
1
>>> b
2
>>> c
3
```

## 4. Set operations

```
>>> a = {1,2,3,6,2,3}
>>> b = {4,2,5,7,4,3}
>>> a
set([1, 2, 3, 6])
>>> a | b
set([1, 2, 3, 4, 5, 6, 7])
>>> a & b
set([2, 3])
>>> a - b
set([1, 6])
>>> a^b
set([1, 4, 5, 6, 7])
```

## 5. nLargest and nSmallest

```
>>> import heapq
>>> a = [3,2,5,6,7,34,8,3,42,4,5]
>>> heapq.nsmallest(5,a)
[2, 3, 3, 4, 5]
>>> heapq.nlargest(3,a)
[42, 34, 8]
```

## 6. Cartesian products

```
>>> import itertools
>>> [print(p) for p in itertools.product([4,3,6,2],[3,6])]
(4, 3)
(4, 6)
(3, 3)
(3, 6)
(6, 3)
(6, 6)
(2, 3)
(2, 6)
```

## 7. Inverting a dictionary

```
>>> a = {'a':1,'b':2,'c':3}
>>> {x: y for y, x in a.items()}
{1: 'a', 2: 'b', 3: 'c'}
```

## 8. Generators

```
>>> a = (x+1 for x in xrange(10))
>>> next(a) 1
>>> next(a) 2
>>> next(a) 3
```

## 9. Named tuples

```
>>> import collections
>>> Point = collections.namedtuple('Point',['x','y'])
>>> p = Point(x=1,y=3)
>>> p
Point(x=1, y=3)
>>> p.x
1
>>> p.y
3
```

## 10. Flatten lists

```
>>> a = [[1,2],[4,3],[5,2]]
>>> sum(a,[])
[1, 2, 4, 3, 5, 2]
```