{"id":166,"date":"2022-11-20T13:20:00","date_gmt":"2022-11-20T13:20:00","guid":{"rendered":"https:\/\/zelazkiewicz.com\/?p=166"},"modified":"2023-03-23T12:22:56","modified_gmt":"2023-03-23T12:22:56","slug":"10-python-tricks-that-you-probably-should-know","status":"publish","type":"post","link":"https:\/\/zelazkiewicz.com\/python\/10-python-tricks-that-you-probably-should-know\/","title":{"rendered":"10 Python Tricks That You Probably Should Know"},"content":{"rendered":"\n<p>Here you can find some Python tricks and tips that might be useful for your everyday coding.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">1. List Comprehensions<\/h2>\n\n\n\n<p>List comprehensions are a concise way to create lists in Python. They are faster and better optimized than traditional for-loops and can be written in a single line of code.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>squares = &#91;x**2 for x in range(10)]\n\nprint(squares)\n\n# Output:\n# &#91;0, 1, 4, 9, 16, 25, 36, 49, 64, 81]<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">2. Lambda functions<\/h2>\n\n\n\n<p>Lambda functions are small anonymous functions that can be defined in a single line of code. They are useful when you need a simple function for a short period of time. They can be used e.g. to provide a sorting function for the sort method of a list.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>f = lambda x: x**2\nprint(f(2))\n# Output: 4\n\npeople = &#91;\n    {\n        'name': 'John',\n    }, {\n        'name': 'Lisa',\n    }, {\n        'name': 'Albreht',\n    }\n]\n\npeople.sort(key=lambda v: v&#91;'name'])\nprint(people)\n# Output:\n# &#91;{'name': 'Albreht'}, {'name': 'John'}, {'name': 'Lisa'}]<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">3. Generators<\/h2>\n\n\n\n<p>Generators are functions that return an iterator. They are used to create large data sets that cannot be stored in memory all at once.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def fibonacci():\n    a, b = 0, 1\n    while True:\n        yield a\n        a, b = b, a + b\n\nfib = fibonacci()\nfor i in range(10):\n    print(next(fib))\n\n# Output:\n# 0\n# 1\n# 1\n# 2\n# 3\n# 5\n# 8\n# 13\n# 21\n# 34<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">4. Context managers<\/h2>\n\n\n\n<p>Context managers are objects that define the behavior of the <code>with<\/code> statement. They are often used to manage resources such as files or network connections.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>with open('file.txt', 'w') as f:\n    f.write('Hello, world!')\n\nwith open('file.txt', 'r') as f:\n    print(f.read())\n\n# Output:\n# Hello, world!<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">5. Decorators<\/h2>\n\n\n\n<p>Decorators are a way to modify or enhance the behavior of a function without changing its code. They are useful when you need to add functionality to multiple functions.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def debug(func):\n    def wrapper(*args, **kwargs):\n        print(f'Calling {func.__name__}()')\n        return func(*args, **kwargs)\n    return wrapper\n\n@debug\ndef add(x, y):\n    return x + y\n\nresult = add(2, 3)\nprint(result)\n\n# Output:\n# Calling add()\n# 5<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">6. Tuple unpacking<\/h2>\n\n\n\n<p>Tuple unpacking is a way to assign multiple variables at once using a single tuple.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>x, y = (1, 2)\n\nprint(x)\nprint(y)\n\n# Output:\n# 1\n# 2<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">7. Zip function<\/h2>\n\n\n\n<p>The <code>zip()<\/code> function is used to combine two or more iterables into a single iterator of tuples.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>names = &#91;'Alice', 'Bob', 'Charlie']\nages = &#91;25, 30, 35]\n\nfor name, age in zip(names, ages):\n    print(f'{name} is {age} years old')\n\n# Output:\n# Alice is 25 years old\n# Bob is 30 years old\n# Charlie is 35 years old<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">8. Defaultdict<\/h2>\n\n\n\n<p>The <code>defaultdict<\/code> is a dictionary-like object that provides a default value for non-existent keys.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>from collections import defaultdict\n\ncolors = defaultdict(lambda: 'unknown')\ncolors&#91;'apple'] = 'red'\n\nprint(colors&#91;'apple'])\nprint(colors&#91;'banana'])\n\n# Output:\n# red\n# unknown<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">9. Enumerate function<\/h2>\n\n\n\n<p>The <code>enumerate()<\/code> function is used to iterate over a sequence and keep track of the index of the current item.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>fruits = &#91;'apple', 'banana', 'cherry']\n\nfor i, fruit in enumerate(fruits):\n    print(f'{i}: {fruit}')\n\n# Output:\n# 0: apple\n# 1: banana\n# 2: cherry<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">10. List slicing<\/h2>\n\n\n\n<p>List slicing is a way to extract a subset of elements from a list.<\/p>\n\n\n\n<p>List slicing takes 3 parameters.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>my_list&#91;start, stop, step]<\/code><\/pre>\n\n\n\n<p>The start is the beginning of a slice, the stop is the end of a slice and the step is the step between the next numbers that are taken into the resulting list.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>numbers = &#91;0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n\nprint(numbers&#91;:3])\n# Output: &#91;0, 1, 2]\n\nprint(numbers&#91;-3:])\n# Output: &#91;10, 11, 12]\n\nprint(numbers&#91;-1:])\n# Output: &#91;12]\n\nprint(numbers&#91;::2])\n# Output: &#91;0, 2, 4, 6, 8, 10, 12]\n\nprint(numbers&#91;::-1])\n# Output: &#91;12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Here you can find some Python tricks and tips that might be useful for your everyday coding. 1. List Comprehensions List comprehensions are a concise way to create lists in Python. They are faster and better optimized than traditional for-loops and can be written in a single line of code. 2. Lambda functions Lambda functions &hellip; <\/p>\n<p class=\"link-more\"><a href=\"https:\/\/zelazkiewicz.com\/python\/10-python-tricks-that-you-probably-should-know\/\" class=\"more-link\">Read more<span class=\"screen-reader-text\"> &#8220;10 Python Tricks That You Probably Should Know&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[9],"tags":[],"featured_media_urls":[],"_links":{"self":[{"href":"https:\/\/zelazkiewicz.com\/wp-json\/wp\/v2\/posts\/166"}],"collection":[{"href":"https:\/\/zelazkiewicz.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zelazkiewicz.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zelazkiewicz.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zelazkiewicz.com\/wp-json\/wp\/v2\/comments?post=166"}],"version-history":[{"count":3,"href":"https:\/\/zelazkiewicz.com\/wp-json\/wp\/v2\/posts\/166\/revisions"}],"predecessor-version":[{"id":169,"href":"https:\/\/zelazkiewicz.com\/wp-json\/wp\/v2\/posts\/166\/revisions\/169"}],"wp:attachment":[{"href":"https:\/\/zelazkiewicz.com\/wp-json\/wp\/v2\/media?parent=166"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zelazkiewicz.com\/wp-json\/wp\/v2\/categories?post=166"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zelazkiewicz.com\/wp-json\/wp\/v2\/tags?post=166"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}