<jupyter_start><jupyter_text>[View in Colaboratory](https://colab.research.google.com/github/DreamsOfBunnies/Python/blob/master/An_A_Z_of_Useful_Python_Tricks.ipynb)  An A-Z of useful Python tricksThis colab is based upon the tricks demonstrated in <NAME>ons freeCodeCamp article *An A-Z of useful Python tricks*.<jupyter_code>%%html
<marquee style='width: 30%; color: blue;'><b>Yay tricks!</b></marqee><jupyter_output><empty_output><jupyter_text>all or any<jupyter_code>x = [True, True, False]

if any(x):
    print("At least one True")
    
if all(x):
    print("Not one False")
else:
    print("All are not True")
    
if any(x) and not all(x):
    print("At least one True and one False")<jupyter_output>At least one True
All are not True
At least one True and one False<jupyter_text>bashplotlibPlot graphs in the console<jupyter_code>!pip install bashplotlib<jupyter_output>Collecting bashplotlib
  Downloading https://files.pythonhosted.org/packages/ac/a7/b0871fd1bcc38a3be7b6d0a188876e5a84c16c52f62dac9fe28418d12fe0/bashplotlib-0.6.5.tar.gz
Building wheels for collected packages: bashplotlib
  Running setup.py bdist_wheel for bashplotlib ... [?25l- done
[?25h  Stored in directory: /root/.cache/pip/wheels/39/f0/8b/6e42f59f24ca2115413dc1a8195a2fb82f9daeed52839aa631
Successfully built bashplotlib
Installing collected packages: bashplotlib
Successfully installed bashplotlib-0.6.5<jupyter_text>collections<jupyter_code>from collections import OrderedDict, Counter

# Remember the order the keys are added!
ordered_dict = OrderedDict(a=1, b=2, c=3)
print(ordered_dict)

# Counts frequency of each character
freqs = Counter("Hello World!")
print(freqs)<jupyter_output>OrderedDict([('a', 1), ('b', 2), ('c', 3)])
Counter({'l': 3, 'o': 2, 'H': 1, 'e': 1, ' ': 1, 'W': 1, 'r': 1, 'd': 1, '!': 1})<jupyter_text>dir<jupyter_code>dir()
dir("Hello World!")
dir(dir)<jupyter_output><empty_output><jupyter_text>emoji[Emoji cheat sheet](https://www.webfx.com/tools/emoji-cheat-sheet/)<jupyter_code>!pip install emoji
from emoji import emojize

print(emojize(":thumbs_up:"))<jupyter_output>👍<jupyter_text>from __future__ import<jupyter_code>from __future__ import braces
from __future__ import print_function

print("Hello World!")<jupyter_output>Hello World!<jupyter_text>geopy<jupyter_code>!pip install geopy
from geopy import GoogleV3

place = "550 Buck Street, Pembroke, NH 03275"
location = GoogleV3().geocode(place)

print(location.address)
print(location.location)<jupyter_output>550 Buck St, Pembroke, NH 03275, USA<jupyter_text>howdoi<jupyter_code>!pip install howdoi
!howdoi find nth fibonacci python<jupyter_output>def fib(n):
    cur = 1
    old = 1
    i = 1
    while (i < n):
        cur, old, i = cur+old, cur, i+1
    return cur

for i in range(10):
    print(fib(i))<jupyter_text>inspect<jupyter_code>import inspect

print(inspect.getsource(inspect.getsource))
print(inspect.getmodule(inspect.getmodule))
print(inspect.currentframe().f_lineno)<jupyter_output>def getsource(object):
    """Return the text of the source code for an object.

    The argument may be a module, class, method, function, traceback, frame,
    or code object.  The source code is returned as a single string.  An
    OSError is raised if the source code cannot be retrieved."""
    lines, lnum = getsourcelines(object)
    return ''.join(lines)

<module 'inspect' from '/usr/lib/python3.6/inspect.py'>
5<jupyter_text>Jedi  **kwargs<jupyter_code>dictionary = {"a": 1, "b": 2}

def someFunction(a, b):
    print(a + b)
    return

# these do the same thing
print(someFunction(**dictionary))
someFunction(a=1, b=2)<jupyter_output>3
None
3<jupyter_text>List comprehensions<jupyter_code>numbers = [1, 2, 3, 4, 5, 6, 7]
evens = [x for x in numbers if x % 2 is 0]
odds = [y for y in numbers if y not in evens]

print("evens: ", evens)
print("odds: ", odds)
cities = ['London', 'Dublin', 'Oslo']

def visit(city):
    print("Welcome to "+city)
    
for city in cities:
    visit(city)<jupyter_output>Welcome to London
Welcome to Dublin
Welcome to Oslo<jupyter_text>map<jupyter_code>x = [1, 2, 3]
y = map(lambda x: x + 1, x)

# applies lambda function to each element in x
list(y)<jupyter_output><empty_output><jupyter_text>[newspaper3k](https://pypi.org/project/newspaper3k)[Quickstart](https://https://newspaper.readthedocs.io/en/latest/user_guide/quickstart.html)<jupyter_code>!pip install newspaper3k
from newspaper import Article

url = 'https://money.cnn.com/2018/08/31/investing/coca-cola-company-costa/index.html'
article = Article(url)
dir(article)
article.download()
article.html
article.parse()
print(article.authors)
print(article.publish_date)
text = article.text
text
article.top_image
# NLP!!!
import nltk
nltk.download('punkt')

article.nlp()

article.keywords
article.summary<jupyter_output><empty_output><jupyter_text>Operator overloadingUsing operators for multiple actions depending on context (ex. '+' for adding integers *or* concatenating strings).<jupyter_code>class Thing:
    def __init__(self, value):
        self.__value = value
    def __gt__(self, other):
        return self.__value > other.__value
    def __lt__(self, other):
        return self.__value < other.__value
    
something = Thing(100)
nothing = Thing(0)

# True
print(something > nothing)

# False
print(something < nothing)

# Error
print(something + nothing)<jupyter_output>True
False<jupyter_text>pprintKinder formatting for long print outputs.<jupyter_code>import requests
import pprint

pprint.pprint(article.summary)<jupyter_output>('The company has agreed to buy coffee chain Costa Coffee from UK drinks and '
 'hotels group Whitbread for £3.9 billion ($5.1 billion).\n'
 'It will give Coca-Cola (KO) "a strong coffee platform across parts of '
 'Europe, Asia Pacific, the Middle East and Africa, with the opportunity for '
 'additional expansion," Coca-Cola said in a statement.\n'
 'Besides its thousands of retail stores, Costa Coffee also has smaller '
 'on-the-go outlets called Costa Express, a roastery and for-home coffee '
 'products.\n'
 'Buying Costa puts Coke in direct competition with Starbucks (SBUX) and '
 'several other global coffee brands.\n'
 '"Costa gives us access to this market with a strong coffee platform."')<jupyter_text>Queuehttps://www.tutorialspoint.com/python3/python_multithreading.htm  __repr__When defining a class or an object in Python, it is useful to provide an ‘official’ way of representing that object as a string. For example:<jupyter_code>file = open('file.txt', 'r')
print(file)<jupyter_output><empty_output><jupyter_text>This makes debugging code a lot easier. Add it to your class definitions as below:<jupyter_code>class someClass:
    def __repr__(self):
        return "<some description here>"

someInstance = someClass()

# prints <some description here>
print(someInstance)<jupyter_output><some description here><jupyter_text>shPython makes a great scripting language. Sometimes using the standard os and subprocess libraries can be a bit of a headache.The [sh library](http://amoffat.github.io/sh/) provides a neat alternative.It lets you call any program as if it were an ordinary function — useful for automating workflows and tasks, all from within Python.<jupyter_code>from sh import *

sh.pwd()
sh.mkdir('new_folder')
sh.touch('new_file.txt')
sh.whoami()
sh.echo('This is great!')<jupyter_output><empty_output><jupyter_text>Type hintsPython is a dynamically-typed language. You don’t need to specify datatypes when you define variables, functions, classes etc.This allows for rapid development times. However, there are few things more annoying than a runtime error caused by a simple typing issue.Since Python 3.5, you have the option to provide type hints when defining functions.<jupyter_code>def addTwo(x : Int) -> Int:
    return x + 2<jupyter_output><empty_output><jupyter_text>You can also define type aliases:<jupyter_code>from typing import List

Vector = List[float]
Matrix = List[Vector]

def addMatrix(a : Matrix, b : Matrix) -> Matrix:
  result = []
  for i,row in enumerate(a):
    result_row =[]
    for j, col in enumerate(row):
      result_row += [a[i][j] + b[i][j]]
    result += [result_row]
  return result

x = [[1.0, 0.0], [0.0, 1.0]]
y = [[2.0, 1.0], [0.0, -2.0]]

z = addMatrix(x, y)<jupyter_output><empty_output><jupyter_text>Although not compulsory, type annotations can make your code easier to understand.They also allow you to use type checking tools to catch those stray TypeErrors before runtime. Probably worthwhile if you are working on large, complex projects!  uuidA quick and easy way to generate Universally Unique IDs (or ‘UUIDs’) is through the Python Standard Library’s uuid module.<jupyter_code>import uuid

user_id = uuid.uuid4()
print(user_id)<jupyter_output><empty_output><jupyter_text>This creates a randomized 128-bit number that will almost certainly be unique.In fact, there are over 2¹²² possible UUIDs that can be generated. That’s over five undecillion (or 5,000,000,000,000,000,000,000,000,000,000,000,000).The probability of finding duplicates in a given set is extremely low. Even with a trillion UUIDs, the probability of a duplicate existing is much, much less than one-in-a-billion.Pretty good for two lines of code.  Virtual environmentsThis is probably my favorite Python thing of all.Chances are you are working on multiple Python projects at any one time. Unfortunately, sometimes two projects will rely on different versions of the same dependency. Which do you install on your system?Luckily, Python’s support for virtual environments lets you have the best of both worlds. From the command line:<jupyter_code>python -m venv my-project
source my-project/bin/activate
pip install all-the-modules<jupyter_output><empty_output><jupyter_text>Now you can have standalone versions and installations of Python running on the same machine. Sorted!  wikipediaWikipedia has a great API that allows users programmatic access to an unrivalled body of completely free knowledge and information.The [wikipedia module](https://wikipedia.readthedocs.io/en/latest/quickstart.html) makes accessing this API almost embarrassingly convenient.<jupyter_code>!pip3 install wikipedia
import wikipedia

result = wikipedia.page('freeCodeCamp')
print(result.summary)
for link in result.links:
    print(link)<jupyter_output>Collecting wikipedia
  Downloading https://files.pythonhosted.org/packages/67/35/25e68fbc99e672127cc6fbb14b8ec1ba3dfef035bf1e4c90f78f24a80b7d/wikipedia-1.4.0.tar.gz
Requirement already satisfied: beautifulsoup4 in /usr/local/lib/python3.6/dist-packages (from wikipedia) (4.6.3)
Requirement already satisfied: requests<3.0.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from wikipedia) (2.18.4)
Requirement already satisfied: idna<2.7,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.0.0->wikipedia) (2.6)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.0.0->wikipedia) (3.0.4)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.0.0->wikipedia) (2018.8.24)
Requirement already satisfied: urllib3<1.23,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from requests<3.0.0,>=2.0.0->wikipedia) (1.22)
Building wheels for collected pac[...]<jupyter_text>Like the real site, the module provides support for multiple languages, page disambiguation, random page retrieval, and even has a donate() method.  xkcdHumour is a key feature of the Python language — after all, it is named after the British comedy sketch show Monty Python’s Flying Circus. Much of Python’s official documentation references the show’s most famous sketches.The sense of humour isn’t restricted to the docs, though. Have a go running the line below:<jupyter_code>import antigravity<jupyter_output><empty_output><jupyter_text>Never change, Python. Never change.  YAMLYAML stands for ‘YAML Ain’t Markup Language’. It is a data formatting language, and is a superset of JSON.Unlike JSON, it can store more complex objects and refer to its own elements. You can also write comments, making it particularly suited to writing configuration files.The PyYAML module lets you use YAML with Python. Install with:<jupyter_code>!pip3 install pyyaml
import yaml<jupyter_output><empty_output><jupyter_text>PyYAML lets you store Python objects of any datatype, and instances of any user-defined classes also.  zipOne last trick for ya, and it really is a cool one. Ever needed to form a dictionary out of two lists?<jupyter_code>keys = ['a', 'b', 'c']
vals = [1, 2, 3]
zipped = dict(zip(keys, vals))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10567885633046363, 'fraction_numerical': 0.028354790300924096, 'mean_word_length': 5.440488301119023, 'pattern_counts': {'":': 3, '<': 115, '<?xml version=': 0, '>': 121, 'https://': 10, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '27', 'dir': 'jupyter-structured-clean-dedup', 'id': '338918', 'license': 'MIT', 'n_tokens_mistral': 4425, 'n_tokens_neox': 4132, 'n_words': 1295, 'path': 'An_A_Z_of_Useful_Python_Tricks.ipynb', 'repo_name': 'DreamsOfBunnies/Python', 'size': '12666'}