GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — python-notes/python-tips.md at main · smenjas/python-notes

Expand file tree

/

python-tips.md

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
66 lines (49 loc) · 1.23 KB
/

python-tips.md

Copy path

File metadata and controls

66 lines (49 loc) · 1.23 KB
Raw
Copy raw file
Download raw file
Outline
Edit and raw actions

Python Tips

Use isinstance(), not type()

type() only tells you the name of the class lowest in the hierarchy. isinstance() tells you whether the object inherits from the given class, so it works for child classes.

List, set, and dictionary comprehensions

my_list = []
for i in range(4):
    my_list.append(i)

my_list = [i for i in range(4)]

my_dict = []
for i in range(4):
    my_dict.append(i)

names = ['Alice', 'Bob', 'Claire']
aliases = ['Angel', 'Bobo', 'Clack']
my_dict = {name: alias for name, alias in zip(names, aliases)}

my_set = set([i for i in range(4)])

Generators

for i in range(4):
    yield i

my_generator = (i for i in range(4))

Iterators

Iterators are objects with iter() and next() methods.

The itertools module helps you efficiently loop through iterables.

import itertools

counter = itertools.count()

Web Scraping

Beautiful Soup makes it easy to parse HTML.

pip install beautifulsoup4
pip install lxml
pip install html5lib
pip install requests
from bs4 import BeautifulSoup
import requests

with open('example.html') as html_file:
    soup = BeautifulSoup(html_file, 'lxml')

print(soup.prettify())

match = soup.title
print(match)
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.