Login
Discover
Waves
Communities
Write
Login
Signup
Topics
#
pytricks
Explore topics
#pytricks
Global
Trending
Hot
New
Payout
Muted
Promoted
#pytricks
New
#pytricks
Follow to get notified about new posts with this tag
Get #pytricks by email
Follow
boyanpro
programming
7y
Python Tricks #9 - Python List Comprehension
# Python program to demonstrate list comprehension in Python # below list contains square of all odd numbers from # range 1 to 10 odd_square = [x ** 2 for x in range(1, 11) if x % 2 == 1] print odd_square
$ 0.123
10
1
boyanpro
programming
7y
Python Tricks #8 - import this
>>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better
$ 0.067
7
1
boyanpro
programming
7y
Python Tricks #7 - True and False are slow
""" True and False are keywords in python3, but not in Python2. In Python2 the value of True is 1, and the value of False is 0. True and False can be regarded as vars and thus they are slow
boyanpro
programming
7y
Python Tricks #6 - Namedtuples
# Why Python is Great: Namedtuples # Using namedtuple is way shorter than # defining a class manually: >>> from collections import namedtuple >>> Car = namedtuple('Car', 'color mileage')
boyanpro
programming
7y
Python Tricks #5
# The get() method on dicts # and its "default" argument name_for_userid = { 382: "Alice", 590: "Bob", 951: "Dilbert", } def greeting(userid): return "Hi %s!"
boyanpro
coding
7y
Python Tricks #4
"""True and False can be used as integer values True -> 1 False -> 0 """ a = 5 print(isinstance(a, int) + (a <= 10)) print(["is odd", "is even"][a
boyanpro
programming
7y
Python Tricks #3
# @classmethod vs @staticmethod vs "plain" methods # What's the difference? class MyClass: def method(self): """ Instance methods need a class instance and can access the instance
boyanpro
programming
7y
Python Tricks #2
# How to sort a Python dict by value # (== get a representation sorted by value) >>> xs = {'a': 4, 'b': 3, 'c': 2, 'd': 1} >>> sorted(xs.items(), key=lambda x: x[1]) [('d', 1), ('c',
boyanpro
coding
7y
Python Tricks #1
# Different ways to test multiple # flags at once in Python x, y, z = 0, 1, 0 if x == 1 or y == 1 or z == 1: print('passed') if 1 in (x, y, z): print('passed') These only test for truthiness: if x or y
← Latest
Discover communities
Explore communities
Create your community