Let's collect simple and profound python tricks here.

This is a part of Python Knowledge and Resources List

  1. Swapping in python

      a, b = b, a

  2. Reversing a list

    my_list = [1, 2, 3]


    print(list(reversed(my_list))) 

    # or
    print my_list[::-1]
    # or (in place)
    my_list.reverse(
    )
  3. Checking if a string is a palindrome

    st = "string"

    if st == st[::-1]:

       print("palindrome")

  4. In Python version 2.x, True and False are not keywords, so

    True = False

    if True == False:

       print “end of the world”

  5. Transposing a matrix

    li=[['a','b','c'],['d','e','f']]

    zip(*li)

  6. Remove duplicates from list.

    list(set(li)) # create unordered list with no duplicates


    #preserve order no duplicates

    from collections import OrderedDict

    d =  OrderedDict()

    for x in li:

        d[x] = 1

    print(list(d.keys()))


    # or a terrible oneliner:

    from collections import OrderedDict

    print OrderedDict(zip(li, [1]*len(li))).keys()


    # or

    from collections import OrderedDict

    print(list(OrderedDict.fromkeys(li)))

  7. Inverting a dictionary using zip (i.e create a list with keys and values swapped)

    dict(zip(di.values(),di.keys()))

    via dictionary comprehension (python >=2.7)

    {v: k for k, v in di.items()}

    dict(map(reversed, di.items()))


  8. Flattening lists

    a=[[1],[2],[3,4],[5,6],[7,8,9]]

    print list(itertools.chain(*a))


    print sum(a,[])

    o/p : [1,2,3,4,5,6,7,8,9]
  9. Getting all the permutations of an iterable

    print list(itertools.permutations([1,2,3]))

  10. Start an http server in a directory

    python -m SimpleHTTPServer 8080 # python 2

    python -m http.server 8080 # python 3

  11. Sort a list of tuples by 2nd item

    from operator import itemgetter

    data = [(1,4,3),(1,2,3),(4,5,6),(7,8,9)]

    data.sort(key=itemgetter(1))

    #alternately with no need to import:

    sorted(data, key = lambda x:x[1])


  12. Unique list that preserves the order of the original (by first occurrence)

    first_list = [1,2,5,4,1,3,5]
    unique_order_maintained = sorted(list(set(first_list)),key=lambda x: first_list.index(x))
    o/p: [1,2,5,4,3]

  13. Rotating a matrix by 90 degrees

    rotated = map(lambda x: list(x), zip(*x[::-1]))

  14. Loading a csv file into a listed dictionary

        listed_dictionary = list(csv.DictReader(open('filename.csv', 'r')))


  15. Flattening lists

    a=[[1],[2],[3,4],[5,6],[7,8,9]]
    print list(a for a in a for a in a)
    o/p : [1,2,3,4,5,6,7,8,9]

    The same but with more readable variable names:

    xss=[[1],[2],[3,4],[5,6],[7,8,9]]
    print list(x for xs in xss for x in xs)

  16. Creating a list without typing a whole lot of commas and quotation marks

    example = 'blue green red purple orange brown white yellow'.split()

  17. Use named tuple instead of a class for simple scenarios+

    from collections import namedtuple

    # define new type
    BuildInput = namedtuple('BuildInput', ['name', 'files'])

    # test scenarios
    b1 = BuildInput('test_build_1', ['file1.txt', 'file2.txt'])
    print(b1) # output: BuildInput(name='test_build_1', files=['test1.txt', 'test2.txt'])

    b2 = BuildInput(name='test_build_2', files=['file3.txt', 'file4.txt'])
    another_b1 = BuildInput(name='test_build_1', files=['file1.txt', 'file2.txt'])

    assert b1 != b2, 'b1 and b2 should be different'
    assert b1 == another_b1, 'b1 and another_b1 should be equal'

  18. Clearing a dictionary and removing a key from a dictionary

    d = {1:'a',2:'b',3:'c'}

    #clearing dictionary
    d.clear()
    #removing a key from a dictionary
    del d[key]
        or
    d.pop(key)

  19. Get lists of different filetypes
    #In this example I used music and picture files
    #but any extensions will work

    import os

    musicfiles = []

    picturefiles = []

    for filename in os.listdir("./example/dir"):

        filetypes = [

            filename.endswith(".ogg") or filename.endswith(".mp3"),

            filename.endswith(".png") or filename.endswith(".jpg")

            ]

        if filetypes[0]:

            musicfiles.append(filename)

        if filetypes[1]:

            picturefiles.append(filename)

  20. Multiple Exit Points in Loop

    # How not to do it

    def find(seq, target):

        found = False

        for i , value in enumerate(seq):

             if value == target:

                 found = True

                 break

             if not found:

                 return -1

             return i

    # How to do it (else on for means if not_break)

    def find(seq, target):

        for i, value in enumerate(seq):

            if value == target:

                break

        else: # Finished the loop and didn't encounter break

            return -1

        return i

  21. First Ocurrence
    Finding the first ocurrence in a collection of data.

    # Non Idiomatic
    found_line = None
    for line in logfile:
       if regex.match(line):
          found_line = line
          break
    return found_line

    # Idiomatic
    return next(line for line in logfile if regex.match(line), None)
Add a Resource to this List
Not more than 250 characters.