forked from ronreiter/interactive-tutorials
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tips.json
2 lines (1 loc) · 23.9 KB
/
tips.json
1
2
[{"hits": 11102, "code": "print [x+1 for x in xrange(10) if x%3 == 0]", "description": "List comprehensions are awesome. They combine map and filter capabilities intuitively.", "title": "List comprehensions", "approved": true, "id": 1}, {"hits": 7091, "code": "my_dict = {}\r\nworld = my_dict.get('hello', 'world')\r\nprint world", "description": "Return a default value if the item isn't in the dictionary", "title": "Dictionary Defaults", "approved": true, "id": 2}, {"hits": 6926, "code": "from math import sqrt \r\n\r\ndef prime(n):\r\n if n < 1 : return False\r\n for d in range(2, int(sqrt(n))+1):\r\n if n % d == 0: return False\r\n return True\r\n\r\nprint [ n for n in range(20) if prime(n) ]\r\nprint filter(prime, range(20))", "description": "You can use filter to select a couple elements from a list, or you can use a list comprehension for the same purpose", "title": "Filter", "approved": true, "id": 4}, {"hits": 6569, "code": "tups = [(1, 4, 7), (2, 5, 8), (3, 6, 9)]\r\nt0s, t1s, t2s = zip(*tups)\r\nprint t0s\r\nprint t1s\r\nprint t2s", "description": "unzip a list of tuples:", "title": "Unzip", "approved": true, "id": 5}, {"hits": 3697, "code": "voters = ['friends','neighbors','countrymen']\r\ncounts = [10,5,800]\r\nprint dict(zip(voters,counts))\r\n\r\nvotes = ['yes',66,'no',77,'abstain',9]\r\nprint dict(zip(votes[:-1:2],votes[1::2]))\r\n", "description": "Create dicts by ziping keys and data", "title": "dict() and zip() make for a powerful combination", "approved": true, "id": 7}, {"hits": 9176, "code": "print \"\"\"Dear John,\r\nHow are you?\r\nBest of luck, George.\"\"\"", "description": "You can use three quotes to code a multi-line string.", "title": "Triple quotes", "approved": true, "id": 1003}, {"hits": 9611, "code": "print map(int, \"10 20 30\".split())", "description": "The Map and filter functions are awesome, and can sometimes provides more readability than list comprehensions.", "title": "Map", "approved": true, "id": 1004}, {"hits": 9721, "code": "import urllib, simplejson, pprint\r\ndata = simplejson.load(urllib.urlopen(\"http://search.twitter.com/search.json?q=learnpython&count=5\"))\r\npprint.pprint([x[\"text\"] for x in data[\"results\"]])\r\n", "description": "Python is really awesome when it comes to API integration. Check out how easy it is to search Twitter:", "title": "Parsing REST API", "approved": true, "id": 1005}, {"hits": 8991, "code": "def get_center():\r\n return (10, 10)\r\n\r\nx, y = get_center()\r\nprint \"The center is at X: %d, Y: %d\" % (x, y)", "description": "Python allows expanding return values from a tuple to several variables:", "title": "Multiple return values", "approved": true, "id": 1006}, {"hits": 9198, "code": "def add(n1, n2):\r\n return n1 + n2\r\n\r\nnumbers = [3, 4]\r\nprint add(*numbers)", "description": "To pass a list of arguments to a function using an array, use the following notation:", "title": "Expanding arrays to function arguments", "approved": true, "id": 1007}, {"hits": 1235, "code": "import itertools\r\nname_generator = itertools.imap(\"name-{}\".format, itertools.count())\r\n# to get the next name:\r\nnew_name = next(name_generator)", "description": "Whenever you need an incremental generator for named objects, you can use this example (2.6+)", "title": "Generate Incrementally unique Names", "approved": true, "id": 1008}, {"hits": 8900, "code": "import collections\r\nd=collections.defaultdict(int)\r\nd[\"never seen before\"] += 1\r\nprint d[\"never seen before\"]", "description": "Check out some useful data types under the \"collections\" package", "title": "Collections", "approved": true, "id": 1009}, {"hits": 8802, "code": "def lottery_numbers():\r\n my_numbers = [1,3,2,5,4,6]\r\n\r\n for n in my_numbers:\r\n if n > 3:\r\n yield n+10\r\n else:\r\n yield n\r\n\r\nfor n in lottery_numbers():\r\n print n", "description": "Python supports generator functions, which create iteratable sequences on the fly:", "title": "Generator Functions", "approved": true, "id": 1010}, {"hits": 9648, "code": "names = ['john', 'peter', 'robert']\r\nages = [24, 26, 35]\r\ncars = ['BMW', 'Audi', 'Ford']\r\n\r\nprint zip(names, ages, cars)", "description": "Combining lists is really easy using zip.", "title": "Zip", "approved": true, "id": 1011}, {"hits": 5504, "code": "def f(*args, **kwargs):\r\n print(args)\r\n print(kwargs)\r\n\r\nf(1,2,3,named1=\"keyword arg1\", another=\"another kwarg\")", "description": "You can accept variable amounts of function parameters by name and by order", "title": "Ordered and Named Function Arguments", "approved": true, "id": 1013}, {"hits": 4505, "code": "world = \"earth\"\r\nprint \"hello %(world)s\" % locals()\r\n", "description": "Use locals for easy string interpolation.", "title": "Locals and strings", "approved": true, "id": 1017}, {"hits": 35669, "code": "from __future__ import division\r\nimport sys\r\n\r\nprint 1/2 + 1/2\r\nprint sys.version", "description": "Integer division can yield floating point results, with an import (or on Python 3, by default)", "title": "Glass half empty?", "approved": true, "id": 1019}, {"hits": 782, "code": "congratulatory_message = list(\"Lucky You!\")\r\n\r\ntemp = congratulatory_message\r\nfor x in range(0,8,4):\r\n temp[x] = chr((7-x)*10)\r\n\r\n# Looks like I never changed the congratulatory message...\r\nprint \"\".join(congratulatory_message)\r\n", "description": "Changing one list can change another list, which can hide bugs or obfuscate code.", "title": "Change mutable lists using another name", "approved": true, "id": 1020}, {"hits": 2262, "code": "import hotshot, hotshot.stats\r\n\r\ndef my_other_func():\r\n for a in xrange(10):\r\n pass\r\n\r\ndef my_func():\r\n for a in xrange(100):\r\n my_other_func()\r\n\r\n# Profile and log...\r\nprof = hotshot.Profile(\"stones.prof\")\r\nprof.runcall(my_func)\r\nprof.close()\r\n\r\n# Print out profiling data\r\nstats = hotshot.stats.load(\"stones.prof\")\r\nstats.print_stats(20)", "description": "Python makes it very easy to profile your code", "title": "Profiling is Easy", "approved": true, "id": 1021}, {"hits": 6805, "code": "print {1, 2, 2, 3, 1}\r\n\r\nnames = [\"Foo\", \"bar\", \"foo\", \"Baz\", \"CATS\", \"dogs\"]\r\nprint {name.upper() for name in names if name[0] in 'fFbB'}", "description": "Python 2.7 supports set literals and comprehensions.", "title": "Set Comprehensions", "approved": true, "id": 2003}, {"hits": 6775, "code": "def talk(text):\r\n print text\r\n\r\ndef think(idea):\r\n print \"thinking about %s\" % idea\r\n\r\ndef do_something(what, with_what):\r\n what(with_what)\r\n\r\ndo_something(talk, 'hello!')\r\ndo_something(think, 'food...')", "description": "Everything is an object. Functions are true objects, so they can be passed as arguments", "title": "Functions as objects", "approved": true, "id": 2005}, {"hits": 7533, "code": "def outside(a, b):\r\n def inside(x):\r\n return x + 5\r\n return inside(a) * inside(b)\r\n\r\nprint outside(1, 2)", "description": "A function can be declared almost anywhere. For example, a function inside a function, like dreaming on Inception :)", "title": "Funception", "approved": true, "id": 2006}, {"hits": 7063, "code": "print eval('+'.join(map(str, [1, 1])))", "description": "How can addition be more easier than this?", "title": "Addition made easy", "approved": true, "id": 2008}, {"hits": 6231, "code": "import sys, StringIO\r\n\r\na=StringIO.StringIO()\r\nold_stdout = sys.stdout\r\nsys.stdout = a\r\nprint \"first print!\"\r\nsys.stdout = old_stdout\r\nprint \"second print?\"\r\nprint a.getvalue()", "description": "You can use it to redirect I/O.", "title": "StringIO", "approved": true, "id": 2009}, {"hits": 3255, "code": "print reduce(lambda a,b: a*b, xrange(1,6))", "description": "Reduce is awesome.", "title": "Reduce", "approved": true, "id": 2012}, {"hits": 2234, "code": "original_list = ['a','b','c']\r\ncopy_of_original_list = original_list\r\ncopy_of_original_list.pop()\r\nprint original_list\r\n\r\n\r\noriginal_list = ['a','b','c']\r\ncopy_of_original_list = original_list[:] # added 3 characters in this statement\r\ncopy_of_original_list.pop()\r\nprint original_list\r\n", "description": "identifiers point to objects, so a change to a mutable object (like a list) will change it no matter how it's identified. To make a copy of a list, slice it, or use copy (or deepcopy).", "title": "Mutability", "approved": true, "id": 2013}, {"hits": 9364, "code": "print \"Hello, World!\"[::-1]", "description": "Reversing a string is really easy:", "title": "Reverse a string", "approved": true, "id": 3002}, {"hits": 6666, "code": "x = ['a','b','c']\r\nprint x[-1]\r\nprint x[:-1]\r\nprint x[-1:]\r\n", "description": "Did you know you can use the subscript notation for reverse lookups?", "title": "Get the last element in a list", "approved": true, "id": 3004}, {"hits": 5941, "code": "import timeit\r\n\r\nt = timeit.Timer(\"for i in range(3): i**2\")\r\nprint t.timeit()\r\n", "description": "Python comes with a handy timeit module to time your code", "title": "Time your code", "approved": true, "id": 3005}, {"hits": 4379, "code": "print sum([[1,2,3], [4,5,6], [7,8,9]], [])", "description": "The second arg to sum() seeds the initial value for sum. The default is 0.", "title": "sum() for merging a list of lists", "approved": true, "id": 3006}, {"hits": 5789, "code": "l = [\"a\", \"b\", \"b\", \"a\", \"c\", \"d\", \"e\", \"a\"]\r\nprint dict([(x, l.count(x)) for x in set(l)])", "description": "Here's a nice one-liner:", "title": "Histogram", "approved": true, "id": 3007}, {"hits": 3168, "code": "def methodOverloadingWithArgs(*args):\r\n if len(args) == 2:\r\n print 'called with 2 arguments'\r\n elif len(args) == 3:\r\n print 'called with 3 arguments'\r\n for arg in args:\r\n print \"passed in \" + arg \r\n\r\n args = (1,2)\r\n methodOverloadingWithArgs(args) #called with 2 arguments\r\n args = (1,2,3)\r\n methodOverloadingWithArgs(args) #called with 3 arguments\r\n\r\ndef methodOverloadingWithKwArgs(**kwargs):\r\n if kwargs[\"arg1\"]:\r\n print \"passed an argument of name arg1 and value\" + kwargs[\"arg1\"]\r\n elif kwargs[\"arg2\"]:\r\n print \"passed an argument of name arg2 and value \" + kwargs[\"arg2\"]\r\n elif kwargs[\"arg3\"]:\r\n print \"passed an argument of name arg3 and value \" + kwargs[\"arg3\"]\r\n\r\nmethodOverloadingWithKwArgs(arg2=\"argument2\",arg1=\"argument1\")\r\nmethodOverloadingWithKwArgs(arg1=\"argument1\",arg2=\"argument2\",arg3=\"argument3\")\r\n \r\n", "description": "You can achieve method overloading by using *args or **kwargs.", "title": "Method Overloading", "approved": true, "id": 3009}, {"hits": 844, "code": "from math import sqrt\r\ndef quad(a, b, c):\r\n return -b/a + sqrt(b**2-4*a*c), -b/a + sqrt(b**2-4*a*c)\r\nroots = lambda a, b, c: (-b/a + sqrt(b**2-4*a*c), -b/a + sqrt(b**2-4*a*c))\r\n#Use with caution.\r\n", "description": "Lambdas are Python's way of telling you to avoid overusing def. ", "title": "Never Define One Line Functions", "approved": true, "id": 3010}, {"hits": 9154, "code": "print \"ABCDEFGH\".encode(\"hex\")\r\nprint 'VGhpcyBpcyBhIHNlY3JldCBNZXNzYWdl\\n'.decode(\"base64\")", "description": "Python supports a wide variety of encoding and decoding methods.", "title": "Encoding & Decoding", "approved": true, "id": 4002}, {"hits": 9204, "code": "\r\ndef failing_print(v):\r\n print('failing_print got %s' % v)\r\ndef any_print(v):\r\n print('any_print got %s' % (v,))\r\n\r\nfor value in (1, True, 'foo', ('tough', 'one')):\r\n for func in (failing_print, any_print):\r\n try:\r\n func(value)\r\n except:\r\n print('%s failed on %s!' % (func.__name__, value))", "description": "While passing a single value to string formatting works, it's dangerous and can fail in subtle ways", "title": "Always pass tuples to string formatting", "approved": true, "id": 4003}, {"hits": 5378, "code": "def func(a, b, c=1, d=1):\r\n return (a * b) + (c * d)\r\n\r\nprint(func(1,2, d=3)) # so a=1, b=2, c=1, d=3", "description": "You can assign function arguments by name, not only by order", "title": "Keyword arguments", "approved": true, "id": 4007}, {"hits": 808, "code": "def bitcount(n):\r\n return bin(n).count('1')\r\n\r\nprint bitcount(1023)", "description": "Count bits in a number", "title": "Count bits in a number", "approved": true, "id": 4008}, {"hits": 4297, "code": "True,False = False,True\r\n\r\nprint False\r\nprint True", "description": "True and false are just variables", "title": "To be or not to be", "approved": true, "id": 4010}, {"hits": 3298, "code": "digit_list = [1,2,3,4,5]\r\nprint reduce(lambda x,y: 10*x+y, digit_list)", "description": "Turn a list of digits to a number.", "title": "Number from Digits", "approved": true, "id": 4012}, {"hits": 6957, "code": "import this", "description": "Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down.", "title": "The Zen of Python", "approved": true, "id": 5002}, {"hits": 8119, "code": "a = 'A'\r\nb = 'B'\r\na,b = b,a\r\nprint 'a', a\r\nprint 'b', b", "description": "Simple notation to swap between variables.", "title": "Swap values", "approved": true, "id": 5005}, {"hits": 38609, "code": "def foobar(arg1, arg2):\r\n return arg1 * arg2\r\n\r\nprint \"Number of arguments:\", foobar.func_code.co_argcount\r\nprint \"Argument names:\", foobar.func_code.co_varnames[:foobar.func_code.co_argcount]", "description": "You can view a lot of information about a function via attributes of the function object, especially it's func_code attribute. The example below takes a function and inspects the arguments it takes", "title": "Inspecting functions", "approved": true, "id": 5006}, {"hits": 6551, "code": "import random\r\nnumbers = range(10)\r\nrandom.shuffle(numbers)\r\nprint numbers", "description": "An example of how to shuffle a list of numbers.", "title": "Bingo", "approved": true, "id": 5012}, {"hits": 4377, "code": "import datetime\r\n\r\ntoday = datetime.datetime.now()\r\nlast_week = today - datetime.timedelta(days=7)\r\nnext_year = today + datetime.timedelta(weeks=52)\r\nprint today\r\nprint last_week\r\nprint next_year", "description": "Work with dates is incredible easy!", "title": "Working with dates", "approved": true, "id": 5014}, {"hits": 0, "code": "class Foo(object):\r\n def bar(self):\r\n print \"This is Foo.bar\"\r\n def baz(self):\r\n print \"and this is Foo.baz\"\r\n\r\nclass FooDecorator(object):\r\n def __init__(self, aFoo):\r\n self._foo = aFoo\r\n\r\n def bar(self):\r\n print \"Decorated\",\r\n foo.bar()\r\n\r\n def __getattr__(self, name):\r\n return getattr(self.foo, name)\r\n\r\ndef test(foo):\r\n foo.bar()\r\n foo.baz()\r\n\r\n>>> test(FooDecorator(Foo()))\r\nDecorated This is Foo.bar\r\nand this is Foo.baz", "description": "Delegation is such a useful technique when reusing software that in python is almost authomatic using the __getattr__ method:", "title": "Simple delegation in Python", "approved": true, "id": 5016}, {"hits": 53000, "code": "print \"me! \" * 5", "description": "If you want to make a string repeat, just multiply it.", "title": "String repetition", "approved": true, "id": 6001}, {"hits": 8684, "code": "data = {\"name\" : \"Alfred\"}\r\nprint \"Hello %(name)s! How are you?\" % data\r\n", "description": "Python has really powerful string formatting. If you want to use dictionary based (template-like) formatting, then you can:", "title": "String formatting using dictionaries", "approved": true, "id": 6003}, {"hits": 6311, "code": "stuff = [1]\r\n\r\n(thing,) = stuff\r\n\r\nprint(thing)", "description": "If you have a list/tuple/set with only one element, and you want to retrieve it, an elegant way would be to use Python's tuple-unpacking syntax.", "title": "Getting the single item out of a list/tuple/set", "approved": true, "id": 6005}, {"hits": 6989, "code": "def get_common_elements(list_of_lists):\r\n return list(set.intersection(*map(set, list_of_lists)))\r\n\r\na = [1,2,3,4,5,6,7,8,9,10]\r\nb = [2,4,6,8,10,12,14,16,18,20]\r\nprint get_common_elements([a,b])\r\nprint list(set.union( set(a), set(b) ))", "description": "Using set operations is powerful. Find the elements common to all lists in a list of lists.", "title": "Sets for finding unions and intersections", "approved": true, "id": 6006}, {"hits": 6319, "code": "def permissive(*args, **kargs):\r\n for value in args:\r\n print str(value)\r\n for name, value in kargs.items():\r\n print name + \"=\" + str(value)\r\n\r\npermissive(1, True, 'hello', name='john', alive=True)", "description": "You can create functions that allow any parameter!", "title": "Permissive functions", "approved": true, "id": 6009}, {"hits": 5285, "code": "print True + True == 2", "description": "Check help(True) for more details.", "title": "Bools inherit from int", "approved": true, "id": 6010}, {"hits": 35306, "code": "print int(\"10101010\", 2)", "description": "Int supports different bases, which is very useful.", "title": "Convert a binary number to an integer", "approved": true, "id": 6012}, {"hits": 9404, "code": "stuff = [4, None, 'foo', [], 'bar', {}, 42, set(), 'baz', 0]\r\nprint filter(bool, stuff)", "description": "Use the filter() built-in function", "title": "Filter out empty values from a list (or any other iterable)", "approved": true, "id": 7001}, {"hits": 6297, "code": "import string\r\n\r\nalphabet = \"abcdefghijklmnopqrstuvwxyz\"\r\nmap = string.maketrans(alphabet, alphabet[::-1])\r\n\r\nprint \"secret message\".translate(map)\r\nprint \"hvxivg nvhhztv\".translate(map)", "description": "string.translate is awesome! Here is an example of a simple \"encryption\" which flips the order of the letters.", "title": "String translation tables", "approved": true, "id": 7004}, {"hits": 12, "code": "first_name, last_name = (\"John\", \"Smith\")\r\nprint(\"First Name: {0}, Last Name: {1}\".format(first_name, last_name))\r\n\r\nsums = [first + second for first, second in [(1,5), (2,4), (3,3)]]", "description": "You can unpack a list or tuple on assignment", "title": "Unpacking collections", "approved": true, "id": 7005}, {"hits": 42246, "code": "names = (\"foo\", \"bar\", \"Foo\", \"Baz\")\r\nfor index, name in enumerate(names):\r\n print index, name\r\n", "description": "Use the built-in enumerate() if you need to use the index too", "title": "Enumerating a list", "approved": true, "id": 7006}, {"hits": 4997, "code": "print sum([1,2,3,4])", "description": "Straight to the point.", "title": "Summing up numbers", "approved": true, "id": 7007}, {"hits": 768, "code": "import math\r\nfrom collections import namedtuple\r\n\r\nPoint = namedtuple(\"Point\", ('x', 'y'))\r\nprint Point(10, 20)\r\n\r\nclass Point2d(Point):\r\n def dist(self, pt):\r\n return math.sqrt((self.x - pt.x) ** 2 + (self.y - pt.y) ** 2)\r\n\r\nprint Point2d(3, 7).dist(Point(4, 6))", "description": "Get rid of boilerplate constructor code.", "title": "namedtuple", "approved": true, "id": 7008}, {"hits": 5577, "code": "import functools\r\n\r\ndef debug(level, text):\r\n print \"%s: %s\" % (level, text)\r\n\r\ninfo = functools.partial(debug, \"INFO\")\r\nerror = functools.partial(debug, \"ERROR\")\r\n\r\ninfo(\"running\")\r\nerror(\"stopped\")\r\n", "description": "Create functions which extend other functions using predefined parameters:", "title": "Partial function", "approved": true, "id": 7009}, {"hits": 807, "code": "class Cat():\r\n def __init__(self, leg):\r\n self.leg = leg\r\n \r\nc = Cat(4)\r\nleg_num = getattr(c, 'leg')\r\nprint leg_num", "description": "Get class attribute with a string", "title": "getattr()", "approved": true, "id": 7010}, {"hits": 789, "code": "# This\r\nsum(x for x in xrange(10))\r\n\r\n# is faster than this\r\nsum([x for x in xrange(10)])\r\n\r\n# and also prettier", "description": "When passing a generator expression to a function like sum(), max(), map(), or filter(), it's faster to use a bare iterator", "title": "Skip the intermediate list", "approved": true, "id": 11001}, {"hits": 2308, "code": "def is_palindrome(str):\r\n return str == str[::-1]\r\n\r\nprint 'racecar is a palindrome?', is_palindrome('racecar')\r\nprint 'helicopter is a palindrome?', is_palindrome('helicopter')", "description": "Checking for palindromes is easy with slices.", "title": "Palindrome", "approved": true, "id": 11002}, {"hits": 38452, "code": "from operator import mul\r\nfactorial = lambda n: reduce(mul, xrange(2, n+1), 1)\r\nprint factorial(21)", "description": "There are probably as many different non-native implementations of the factorial function in Python as there are stars in the sky, but this one shines particularly bright. This lambda function uses reduce to iterate through numbers from 2 to n, multiplying them as it goes along. Note that the third argument to reduce is the default value, which is returned if the sequence given by xrange is empty (e.g. if n is zero or one).", "title": "Factorial function", "approved": true, "id": 11003}, {"hits": 2270, "code": "import math\r\n\r\nfloat(2.00).__pow__(float(math.pi.__mul__(float(1.00).__div__(math.pi))).__div__(float(2.00)))", "description": "Finding the square root of a number is super easy!", "title": "Square Roots", "approved": true, "id": 12002}, {"hits": 811, "code": "things = [1,2,'3','dog']\r\nnumbers = [t for t in things if t.isdigit()]", "description": "You can add conditions to your list comprehensions", "title": "List Comprehensions Support Conditionals", "approved": true, "id": 13001}, {"hits": 860, "code": "five = 10 - 2 + 3 - 6\r\nprint \"This should be five: %s\" % five", "description": "", "title": "%d and %s can turn to the same thing", "approved": true, "id": 17001}, {"hits": 811, "code": "class Cat(object):\r\n def sit(self):\r\n print \"Cat sits down\"\r\n\r\nclass Dog(object):\r\n def sit(self):\r\n print \"Dog sits down\"\r\n\r\ndef makeAnimal(animal):\r\n if animal is \"Dog\":\r\n class InheritedAnimal(Dog):\r\n pass\r\n return InheritedAnimal\r\n if animal is \"Cat\":\r\n class InheritedAnimal(Cat):\r\n pass\r\n return InheritedAnimal\r\n\r\nMyAnimal = makeAnimal(\"Dog\")\r\nmy_dog = MyAnimal()\r\nmy_dog.sit()", "description": "Dynamically inherit a class with factory-like pattern", "title": "Dynamic inheritance", "approved": true, "id": 18001}, {"hits": 0, "code": "fibo = [1,1]\r\nfor x in range(3,100):\r\n\tfibo.append(fibo[x-2]+fibo[x-3])\r\nprint fibo\r\n", "description": "appending elements to a list is easy!", "title": "fibonaci sequnce", "approved": true, "id": 28001}, {"hits": 931, "code": "python -m SimpleHTTPServer", "description": "You can start a simple http server on any directory without any hassle with just one command.", "title": "Start simple HTTP Server in seconds", "approved": true, "id": 31001}, {"hits": 894, "code": "from random import shuffle\r\n\r\nteam1 = ['John', 'Dave', 'Melissa', 'Kim', 'Hank', 'Russ']\r\nteam2 = [team1.pop() for member in (shuffle(team1) or team1)]\r\n\r\nprint \"member in team 1 is\", team1\r\nprint \"member in team 2 is\", team2", "description": "Popping while iterating make list get smaller and smaller.", "title": "Popping while iterating", "approved": true, "id": 34001}, {"hits": 0, "code": "import this", "description": "Zen of python", "title": "This", "approved": true, "id": 36001}, {"hits": 2, "code": "first_names= [(1,'bob'), (2,'bill'), (3,'tim')]\r\n\r\npage_views = [(1, 'home',34),(1,'profile', 5),(2,'home',44),(3,'profile',10)]\r\n\r\njoined_lists = [name + view for name in first_names for view in page_views if name[0] == view[0]]\r\n\r\nprint joined_lists", "description": "You can use list comprehension to join 2 ", "title": "Joins implemented as list comprehesions", "approved": true, "id": 47001}, {"hits": 0, "code": ">>> int('100', 0), int('0x100', 0), int('0100', 0)", "description": "If one wish to convert a string to an integer, but he doesn't know what base the string is he can set the base to 0", "title": "A better string to int casting", "approved": true, "id": 5695057915019264}]