Repository: Chalarangelo/30-seconds-of-python Branch: master Commit: 42680a0cd6f7 Files: 168 Total size: 114.4 KB Directory structure: gitextract_nylby5hi/ ├── .gitattributes ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── language_fix.py ├── snippet-template.md └── snippets/ ├── add-days.md ├── all-equal.md ├── all-unique.md ├── arithmetic-progression.md ├── average-by.md ├── average.md ├── bifurcate-by.md ├── bifurcate.md ├── binomial-coefficient.md ├── byte-size.md ├── camel.md ├── capitalize-every-word.md ├── capitalize.md ├── cast-list.md ├── celsius-to-fahrenheit.md ├── check-prop.md ├── chunk-into-n.md ├── chunk.md ├── clamp-number.md ├── collect-dictionary.md ├── combine-values.md ├── compact.md ├── compose-right.md ├── compose.md ├── count-by.md ├── count-occurrences.md ├── cumsum.md ├── curry.md ├── daterange.md ├── days-ago.md ├── days-diff.md ├── days-from-now.md ├── decapitalize.md ├── deep-flatten.md ├── degrees-to-rads.md ├── delay.md ├── dict-to-list.md ├── difference-by.md ├── difference.md ├── digitize.md ├── drop-right.md ├── drop.md ├── every-nth.md ├── every.md ├── factorial.md ├── fahrenheit-to-celsius.md ├── fibonacci.md ├── filter-non-unique.md ├── filter-unique.md ├── find-index-of-all.md ├── find-index.md ├── find-key.md ├── find-keys.md ├── find-last-index.md ├── find-last.md ├── find-parity-outliers.md ├── find.md ├── flatten.md ├── for-each-right.md ├── for-each.md ├── frequencies.md ├── from-iso-date.md ├── gcd.md ├── geometric-progression.md ├── get.md ├── group-by.md ├── hamming-distance.md ├── has-duplicates.md ├── have-same-contents.md ├── head.md ├── hex-to-rgb.md ├── in-range.md ├── includes-all.md ├── includes-any.md ├── index-of-all.md ├── initial.md ├── initialize-2-d-list.md ├── initialize-list-with-range.md ├── initialize-list-with-values.md ├── intersection-by.md ├── intersection.md ├── invert-dictionary.md ├── is-anagram.md ├── is-contained-in.md ├── is-divisible.md ├── is-empty.md ├── is-even.md ├── is-odd.md ├── is-prime.md ├── is-weekday.md ├── is-weekend.md ├── kebab.md ├── key-in-dict.md ├── key-of-max.md ├── key-of-min.md ├── keys-only.md ├── km-to-miles.md ├── last.md ├── lcm.md ├── longest-item.md ├── map-dictionary.md ├── map-values.md ├── max-by.md ├── max-element-index.md ├── max-n.md ├── median.md ├── merge-dictionaries.md ├── merge.md ├── miles-to-km.md ├── min-by.md ├── min-element-index.md ├── min-n.md ├── months-diff.md ├── most-frequent.md ├── n-times-string.md ├── none.md ├── num-to-range.md ├── offset.md ├── pad-number.md ├── pad.md ├── palindrome.md ├── pluck.md ├── powerset.md ├── rads-to-degrees.md ├── reverse-number.md ├── reverse.md ├── rgb-to-hex.md ├── roll.md ├── sample.md ├── shuffle.md ├── similarity.md ├── slugify.md ├── snake.md ├── some.md ├── sort-by-indexes.md ├── sort-dict-by-key.md ├── sort-dict-by-value.md ├── split-lines.md ├── spread.md ├── sum-by.md ├── sum-of-powers.md ├── symmetric-difference-by.md ├── symmetric-difference.md ├── tail.md ├── take-right.md ├── take.md ├── to-binary.md ├── to-dictionary.md ├── to-hex.md ├── to-iso-date.md ├── to-roman-numeral.md ├── transpose.md ├── unfold.md ├── union-by.md ├── union.md ├── unique-elements.md ├── values-only.md ├── weighted-average.md ├── when.md └── words.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitattributes ================================================ src/docs/* linguist-documentation scripts/* linguist-documentation gatsby-browser.js linguist-documentation gatsby-config.js linguist-documentation gatsby-node.js linguist-documentation gatsby-ssr.js linguist-documentation .travis/* linguist-documentation config.js linguist-documentation ================================================ FILE: .gitignore ================================================ # IDE Specific .vscode .idea/codeStyles/Project.xml # dotenv environment variables file .env # gatsby files .cache/ public # Mac files .DS_Store # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* # Runtime data pids *.pid *.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage # nyc test coverage .nyc_output # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) bower_components # node-waf configuration .lock-wscript # Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules/ jspm_packages/ # TypeScript v1 declaration files typings/ # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz # Yarn yarn-error.log .pnp/ .pnp.js # Yarn Integrity file .yarn-integrity # dotenv environment variables file .env # next.js build output .next ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [mst10041967@gmail.com]. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org ================================================ FILE: CONTRIBUTING.md ================================================ # Contribution Guidelines **30 seconds of code** is powered by the community, so feel free to contribute in any way you can to help us! ## How you can help - Submit pull requests with new snippets (see guidelines below) or snippet updates (tags, descriptions, explanations, typos, examples, code improvements). - Open issues for things you want to see added, modified, discuss ideas or help out with existing issues. ## Ground rules Breaking any of these rules will result in your pull request being closed. Please follow these guidelines above all else: - **Always be polite and respectful to others** and try to follow the advice of the moderators/collaborators/owners. - **Only modify snippet files**, never modify the generated files in the `snippet_data` directory. - **Use the snippet template** to create new snippets, ensure they have the correct name and are in the correct location. - **Follow snippet format exactly**, otherwise your snippets will not be recognized correctly by the tools responsible for publishing them on the website. This includes such things as spacing and empty lines - if you accidentally make a mistake, consult the repository's [snippet template](snippet-template.md). - **Snippets should solve real-world problems**, no matter how simple and should be abstract enough to be applied to different scenarios. ## Snippet creation In order to create a new snippet, you should follow the steps below: - Create a copy of the [snippet template](snippet-template.md) in the `snippets` directory. - Change the name of the newly created file to the name of your snippet. - Edit the file, adding your snippet based on the guidelines. ## Snippet guidelines - Snippet must follow [these general writing guidelines](https://github.com/30-seconds/brand-and-design/blob/master/writing-guidelines.md). - Snippets must have all their frontmatter sections (title, tags etc.) filled. - Snippet titles must correspond to the filename and follow the language and repository's naming conventions. - Snippet tags must be comma-separated, contain a primary tag as seen on the website as their first tag. - Snippets must have their `firstSeen` dates formatted using [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601). - Snippet descriptions must be short and to the point. Explain *what* the snippet does and detail *how* the snippet works and the language features used in it. - Snippet code and examples must be enclosed in appropriate, language-tagged blocks as shown in the snippet template, be short and use modern techniques and features. Also make sure to test your code before submitting. - If your snippet contains arguments with default parameters, explain what happens if they are omitted when calling the function and what the default case is. Specify default parameters for arguments only if necessary. - If your snippet uses recursion, use the `recursion` tag and explain the base cases. - Try to strike a balance between readability, brevity, and performance. - Always use soft tabs (2 spaces), never hard tabs. - Leave a single space after a comma (`,`) character (both in the description and code). - Define multiple variables on the same line, if possible. Use meaningful names (e.g. `letter` instead of `lt`) and follow existing conventions as seen in other snippets. Do not use trailing or leading underscores in variable names. - Snippet should only use native `python 3.6` modules. Snippets using external modules will be disqualified immediately. ================================================ FILE: LICENSE ================================================ Attribution 4.0 International ======================================================================= Creative Commons Corporation ("Creative Commons") is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an "as-is" basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. Using Creative Commons Public Licenses Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. Considerations for licensors: Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC- licensed material, or material used under an exception or limitation to copyright. More considerations for licensors: wiki.creativecommons.org/Considerations_for_licensors Considerations for the public: By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor's permission is not necessary for any reason--for example, because of any applicable exception or limitation to copyright--then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. More considerations for the public: wiki.creativecommons.org/Considerations_for_licensees ======================================================================= Creative Commons Attribution 4.0 International Public License By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. Section 1 -- Definitions. a. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. b. Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. c. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. d. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. e. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. f. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. g. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. h. Licensor means the individual(s) or entity(ies) granting rights under this Public License. i. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. j. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. k. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. Section 2 -- Scope. a. License grant. 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: a. reproduce and Share the Licensed Material, in whole or in part; and b. produce, reproduce, and Share Adapted Material. 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 3. Term. The term of this Public License is specified in Section 6(a). 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a) (4) never produces Adapted Material. 5. Downstream recipients. a. Offer from the Licensor -- Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. b. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). b. Other rights. 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 2. Patent and trademark rights are not licensed under this Public License. 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties. Section 3 -- License Conditions. Your exercise of the Licensed Rights is expressly made subject to the following conditions. a. Attribution. 1. If You Share the Licensed Material (including in modified form), You must: a. retain the following if it is supplied by the Licensor with the Licensed Material: i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); ii. a copyright notice; iii. a notice that refers to this Public License; iv. a notice that refers to the disclaimer of warranties; v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; b. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and c. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. Section 4 -- Sui Generis Database Rights. Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. Section 5 -- Disclaimer of Warranties and Limitation of Liability. a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. Section 6 -- Term and Termination. a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 2. upon express reinstatement by the Licensor. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. Section 7 -- Other Terms and Conditions. a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. Section 8 -- Interpretation. a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. ======================================================================= Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at creativecommons.org/policies, Creative Commons does not authorize the use of the trademark "Creative Commons" or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. Creative Commons may be contacted at creativecommons.org. ================================================ FILE: README.md ================================================ > **IMPORTANT NOTICE:** > > As of May, 2023, all 30-seconds content repositories have been merged into [30-seconds-of-code](https://github.com/30-seconds/30-seconds-of-code). > > Please watch, star and follow relevant activity there. [![Logo](/logo.png)](https://30secondsofcode.org/python/p/1) # 30 seconds of code > Short Python code snippets for all your development needs * Visit [our website](https://30secondsofcode.org) to view our snippet collection. * Use the [Search page](https://30secondsofcode.org/search) to find snippets that suit your needs. You can search by name, tag, language or using a snippet's description. Just start typing a term and see what comes up. * Browse the [Python Snippet collection](https://30secondsofcode.org/python/p/1) to see all the snippets in this project or click individual tags at the top of the same page to narrow down your search to a specific tag. * Click on each snippet card to view the whole snippet, including code, explanation and examples. * You can use the button at the bottom of a snippet card to copy the code to clipboard. * If you like the project, give it a star. It means a lot to the people maintaining it. ## Want to contribute? * If you want to help us improve, take a minute to read the [Contribution Guidelines](/CONTRIBUTING.md) first. * Use the [Snippet Template](/snippet-template.md) to add new snippets to the collection. * If you find a problem with a specific snippet, please [open an issue](https://github.com/30-seconds/30-seconds-of-python/issues/new). * If you find a problem with the website, please [report it in the web repository](https://github.com/30-seconds/30-seconds-web/issues/new). ## Credits * This repository is maintained by the [30 seconds of code organization on GitHub](https://github.com/30-seconds). * All snippets are licensed under the CC-BY-4.0 License, unless explicitly stated otherwise. * Logos, names and trademarks are not to be used without the explicit consent of the owners of the 30 seconds of code GitHub organization. * Our website is powered by [Netlify](https://www.netlify.com/), [Next.js](https://nextjs.org/) & [GitHub](https://github.com/). ================================================ FILE: language_fix.py ================================================ print('This file is here only to tag the repository language. Do not delete, please!') ================================================ FILE: snippet-template.md ================================================ --- title: Function name type: snippet tags: [utility] cover: image dateModified: 2021-06-13T05:00:00-04:00 --- Explain briefly what the snippet does. - Explain briefly how the snippet works. - Use bullet points for your snippet's explanation. - Try to explain everything briefly but clearly. ```py def function_name(args): # code return 0 ``` ```py function_name(val) # result ``` ================================================ FILE: snippets/add-days.md ================================================ --- title: Add days to date type: snippet tags: [date] cover: orange-flower dateModified: 2020-10-28T16:19:04+02:00 --- Calculates the date of `n` days from the given date. - Use `datetime.timedelta` and the `+` operator to calculate the new `datetime.datetime` value after adding `n` days to `d`. - Omit the second argument, `d`, to use a default value of `datetime.today()`. ```py from datetime import datetime, timedelta def add_days(n, d = datetime.today()): return d + timedelta(n) ``` ```py from datetime import date add_days(5, date(2020, 10, 25)) # date(2020, 10, 30) add_days(-5, date(2020, 10, 25)) # date(2020, 10, 20) ``` ================================================ FILE: snippets/all-equal.md ================================================ --- title: Check if list elements are identical type: snippet tags: [list] cover: fallen-leaves dateModified: 2020-10-11T13:40:42+03:00 --- Checks if all elements in a list are equal. - Use `set()` to eliminate duplicate elements and then use `len()` to check if length is `1`. ```py def all_equal(lst): return len(set(lst)) == 1 ``` ```py all_equal([1, 2, 3, 4, 5, 6]) # False all_equal([1, 1, 1, 1]) # True ``` ================================================ FILE: snippets/all-unique.md ================================================ --- title: Check if list has no duplicates type: snippet tags: [list] cover: touch-flower dateModified: 2021-01-07T23:30:28+02:00 --- Checks if all the values in a list are unique. - Use `set()` on the given list to keep only unique occurrences. - Use `len()` to compare the length of the unique values to the original list. ```py def all_unique(lst): return len(lst) == len(set(lst)) ``` ```py x = [1, 2, 3, 4, 5, 6] y = [1, 2, 2, 3, 4, 5] all_unique(x) # True all_unique(y) # False ``` ================================================ FILE: snippets/arithmetic-progression.md ================================================ --- title: Arithmetic progression type: snippet tags: [math] cover: number-2 dateModified: 2020-11-02T19:27:07+02:00 --- Generates a list of numbers in the arithmetic progression starting with the given positive integer and up to the specified limit. - Use `range()` and `list()` with the appropriate start, step and end values. ```py def arithmetic_progression(n, lim): return list(range(n, lim + 1, n)) ``` ```py arithmetic_progression(5, 25) # [5, 10, 15, 20, 25] ``` ================================================ FILE: snippets/average-by.md ================================================ --- title: Mapped list average type: snippet tags: [math,list] cover: flower-vase dateModified: 2020-11-02T19:27:07+02:00 --- Calculates the average of a list, after mapping each element to a value using the provided function. - Use `map()` to map each element to the value returned by `fn`. - Use `sum()` to sum all of the mapped values, divide by `len(lst)`. - Omit the last argument, `fn`, to use the default identity function. ```py def average_by(lst, fn = lambda x: x): return sum(map(fn, lst), 0.0) / len(lst) ``` ```py average_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda x: x['n']) # 5.0 ``` ================================================ FILE: snippets/average.md ================================================ --- title: Average type: snippet tags: [math,list] cover: digital-nomad-15 dateModified: 2020-11-02T19:27:07+02:00 --- Calculates the average of two or more numbers. - Use `sum()` to sum all of the `args` provided, divide by `len()`. ```py def average(*args): return sum(args, 0.0) / len(args) ``` ```py average(*[1, 2, 3]) # 2.0 average(1, 2, 3) # 2.0 ``` ================================================ FILE: snippets/bifurcate-by.md ================================================ --- title: Bifurcate list based on function type: snippet tags: [list] cover: two-flower-vases dateModified: 2020-11-02T19:27:07+02:00 --- Splits values into two groups, based on the result of the given filtering function. - Use a list comprehension to add elements to groups, based on the value returned by `fn` for each element. - If `fn` returns a truthy value for any element, add it to the first group, otherwise add it to the second group. ```py def bifurcate_by(lst, fn): return [ [x for x in lst if fn(x)], [x for x in lst if not fn(x)] ] ``` ```py bifurcate_by(['beep', 'boop', 'foo', 'bar'], lambda x: x[0] == 'b') # [ ['beep', 'boop', 'bar'], ['foo'] ] ``` ================================================ FILE: snippets/bifurcate.md ================================================ --- title: Bifurcate list based on values type: snippet tags: [list] cover: mug-flower-book dateModified: 2020-11-02T19:27:07+02:00 --- Splits values into two groups, based on the result of the given `filter` list. - Use a list comprehension and `zip()` to add elements to groups, based on `filter`. - If `filter` has a truthy value for any element, add it to the first group, otherwise add it to the second group. ```py def bifurcate(lst, filter): return [ [x for x, flag in zip(lst, filter) if flag], [x for x, flag in zip(lst, filter) if not flag] ] ``` ```py bifurcate(['beep', 'boop', 'foo', 'bar'], [True, True, False, True]) # [ ['beep', 'boop', 'bar'], ['foo'] ] ``` ================================================ FILE: snippets/binomial-coefficient.md ================================================ --- title: Binomial coefficient type: snippet tags: [math] cover: digital-nomad-5 dateModified: 2020-11-02T19:27:07+02:00 --- Calculates the number of ways to choose `k` items from `n` items without repetition and without order. - Use `math.comb()` to calculate the binomial coefficient. ```py from math import comb def binomial_coefficient(n, k): return comb(n, k) ``` ```py binomial_coefficient(8, 2) # 28 ``` ================================================ FILE: snippets/byte-size.md ================================================ --- title: Byte size of string type: snippet tags: [string] cover: river-house-lights dateModified: 2020-11-02T19:27:07+02:00 --- Returns the length of a string in bytes. - Use `str.encode()` to encode the given string and return its length. ```py def byte_size(s): return len(s.encode('utf-8')) ``` ```py byte_size('😀') # 4 byte_size('Hello World') # 11 ``` ================================================ FILE: snippets/camel.md ================================================ --- title: Camelcase string type: snippet tags: [string,regexp] cover: digital-nomad-9 dateModified: 2020-11-02T19:27:07+02:00 --- Converts a string to camelcase. - Use `re.sub()` to replace any `-` or `_` with a space, using the regexp `r"(_|-)+"`. - Use `str.title()` to capitalize the first letter of each word and convert the rest to lowercase. - Finally, use `str.replace()` to remove spaces between words. ```py from re import sub def camel(s): s = sub(r"(_|-)+", " ", s).title().replace(" ", "") return ''.join([s[0].lower(), s[1:]]) ``` ```py camel('some_database_field_name') # 'someDatabaseFieldName' camel('Some label that needs to be camelized') # 'someLabelThatNeedsToBeCamelized' camel('some-javascript-property') # 'someJavascriptProperty' camel('some-mixed_string with spaces_underscores-and-hyphens') # 'someMixedStringWithSpacesUnderscoresAndHyphens' ``` ================================================ FILE: snippets/capitalize-every-word.md ================================================ --- title: Capitalize every word type: snippet tags: [string] cover: trippy-chemicals dateModified: 2020-11-02T19:27:07+02:00 --- Capitalizes the first letter of every word in a string. - Use `str.title()` to capitalize the first letter of every word in the string. ```py def capitalize_every_word(s): return s.title() ``` ```py capitalize_every_word('hello world!') # 'Hello World!' ``` ================================================ FILE: snippets/capitalize.md ================================================ --- title: Capitalize string type: snippet tags: [string] cover: palm-tree-house dateModified: 2020-11-02T19:27:07+02:00 --- Capitalizes the first letter of a string. - Use list slicing and `str.upper()` to capitalize the first letter of the string. - Use `str.join()` to combine the capitalized first letter with the rest of the characters. - Omit the `lower_rest` parameter to keep the rest of the string intact, or set it to `True` to convert to lowercase. ```py def capitalize(s, lower_rest = False): return ''.join([s[:1].upper(), (s[1:].lower() if lower_rest else s[1:])]) ``` ```py capitalize('fooBar') # 'FooBar' capitalize('fooBar', True) # 'Foobar' ``` ================================================ FILE: snippets/cast-list.md ================================================ --- title: Cast to list type: snippet tags: [list] cover: colorful-pots dateModified: 2020-11-02T19:27:07+02:00 --- Casts the provided value as a list if it's not one. - Use `isinstance()` to check if the given value is enumerable. - Return it by using `list()` or encapsulated in a list accordingly. ```py def cast_list(val): return list(val) if isinstance(val, (tuple, list, set, dict)) else [val] ``` ```py cast_list('foo') # ['foo'] cast_list([1]) # [1] cast_list(('foo', 'bar')) # ['foo', 'bar'] ``` ================================================ FILE: snippets/celsius-to-fahrenheit.md ================================================ --- title: Celsius to Fahrenheit type: snippet tags: [math] unlisted: true cover: last-light dateModified: 2021-01-04T12:47:04+02:00 --- Converts Celsius to Fahrenheit. - Follow the conversion formula `F = 1.8 * C + 32`. ```py def celsius_to_fahrenheit(degrees): return ((degrees * 1.8) + 32) ``` ```py celsius_to_fahrenheit(180) # 356.0 ``` ================================================ FILE: snippets/check-prop.md ================================================ --- title: Check property type: snippet tags: [function] cover: lake-trees dateModified: 2020-11-02T19:27:07+02:00 --- Creates a function that will invoke a predicate function for the specified property on a given dictionary. - Return a `lambda` function that takes a dictionary and applies the predicate function, `fn` to the specified property. ```py def check_prop(fn, prop): return lambda obj: fn(obj[prop]) ``` ```py check_age = check_prop(lambda x: x >= 18, 'age') user = {'name': 'Mark', 'age': 18} check_age(user) # True ``` ================================================ FILE: snippets/chunk-into-n.md ================================================ --- title: Split list into n chunks type: snippet tags: [list] cover: succulent-10 dateModified: 2020-10-23T05:35:06+03:00 --- Chunks a list into `n` smaller lists. - Use `math.ceil()` and `len()` to get the size of each chunk. - Use `list()` and `range()` to create a new list of size `n`. - Use `map()` to map each element of the new list to a chunk the length of `size`. - If the original list can't be split evenly, the final chunk will contain the remaining elements. ```py from math import ceil def chunk_into_n(lst, n): size = ceil(len(lst) / n) return list( map(lambda x: lst[x * size:x * size + size], list(range(n))) ) ``` ```py chunk_into_n([1, 2, 3, 4, 5, 6, 7], 4) # [[1, 2], [3, 4], [5, 6], [7]] ``` ================================================ FILE: snippets/chunk.md ================================================ --- title: Split list into chunks type: snippet tags: [list] cover: red-berries dateModified: 2020-11-02T19:27:07+02:00 --- Chunks a list into smaller lists of a specified size. - Use `list()` and `range()` to create a list of the desired `size`. - Use `map()` on the list and fill it with splices of the given list. - Finally, return the created list. ```py from math import ceil def chunk(lst, size): return list( map(lambda x: lst[x * size:x * size + size], list(range(ceil(len(lst) / size))))) ``` ```py chunk([1, 2, 3, 4, 5], 2) # [[1, 2], [3, 4], [5]] ``` ================================================ FILE: snippets/clamp-number.md ================================================ --- title: Clamp number type: snippet tags: [math] cover: highlands dateModified: 2020-11-02T19:27:07+02:00 --- Clamps `num` within the inclusive range specified by the boundary values. - If `num` falls within the range (`a`, `b`), return `num`. - Otherwise, return the nearest number in the range. ```py def clamp_number(num, a, b): return max(min(num, max(a, b)), min(a, b)) ``` ```py clamp_number(2, 3, 5) # 3 clamp_number(1, -1, -5) # -1 ``` ================================================ FILE: snippets/collect-dictionary.md ================================================ --- title: Invert dictionary type: snippet tags: [dictionary] cover: working-bee dateModified: 2020-11-02T19:27:07+02:00 --- Inverts a dictionary with non-unique hashable values. - Create a `collections.defaultdict` with `list` as the default value for each key. - Use `dictionary.items()` in combination with a loop to map the values of the dictionary to keys using `dict.append()`. - Use `dict()` to convert the `collections.defaultdict` to a regular dictionary. ```py from collections import defaultdict def collect_dictionary(obj): inv_obj = defaultdict(list) for key, value in obj.items(): inv_obj[value].append(key) return dict(inv_obj) ``` ```py ages = { 'Peter': 10, 'Isabel': 10, 'Anna': 9, } collect_dictionary(ages) # { 10: ['Peter', 'Isabel'], 9: ['Anna'] } ``` ================================================ FILE: snippets/combine-values.md ================================================ --- title: Combine dictionary values type: snippet tags: [dictionary] cover: fruit-feast dateModified: 2021-04-04T14:32:35+03:00 --- Combines two or more dictionaries, creating a list of values for each key. - Create a new `collections.defaultdict` with `list` as the default value for each key and loop over `dicts`. - Use `dict.append()` to map the values of the dictionary to keys. - Use `dict()` to convert the `collections.defaultdict` to a regular dictionary. ```py from collections import defaultdict def combine_values(*dicts): res = defaultdict(list) for d in dicts: for key in d: res[key].append(d[key]) return dict(res) ``` ```py d1 = {'a': 1, 'b': 'foo', 'c': 400} d2 = {'a': 3, 'b': 200, 'd': 400} combine_values(d1, d2) # {'a': [1, 3], 'b': ['foo', 200], 'c': [400], 'd': [400]} ``` ================================================ FILE: snippets/compact.md ================================================ --- title: Compact list type: snippet tags: [list] cover: new-plant dateModified: 2020-11-02T19:27:07+02:00 --- Removes falsy values from a list. - Use `filter()` to filter out falsy values (`False`, `None`, `0`, and `""`). ```py def compact(lst): return list(filter(None, lst)) ``` ```py compact([0, 1, False, 2, '', 3, 'a', 's', 34]) # [ 1, 2, 3, 'a', 's', 34 ] ``` ================================================ FILE: snippets/compose-right.md ================================================ --- title: Reverse compose functions type: snippet tags: [function] cover: lavender-shelf dateModified: 2020-11-02T19:27:07+02:00 --- Performs left-to-right function composition. - Use `functools.reduce()` to perform left-to-right function composition. - The first (leftmost) function can accept one or more arguments; the remaining functions must be unary. ```py from functools import reduce def compose_right(*fns): return reduce(lambda f, g: lambda *args: g(f(*args)), fns) ``` ```py add = lambda x, y: x + y square = lambda x: x * x add_and_square = compose_right(add, square) add_and_square(1, 2) # 9 ``` ================================================ FILE: snippets/compose.md ================================================ --- title: Compose functions type: snippet tags: [function] cover: tram-car-2 dateModified: 2020-11-02T19:27:07+02:00 --- Performs right-to-left function composition. - Use `functools.reduce()` to perform right-to-left function composition. - The last (rightmost) function can accept one or more arguments; the remaining functions must be unary. ```py from functools import reduce def compose(*fns): return reduce(lambda f, g: lambda *args: f(g(*args)), fns) ``` ```py add5 = lambda x: x + 5 multiply = lambda x, y: x * y multiply_and_add_5 = compose(add5, multiply) multiply_and_add_5(5, 2) # 15 ``` ================================================ FILE: snippets/count-by.md ================================================ --- title: Count grouped elements type: snippet tags: [list] cover: rabbit-call dateModified: 2020-11-02T19:27:07+02:00 --- Groups the elements of a list based on the given function and returns the count of elements in each group. - Use `collections.defaultdict` to initialize a dictionary. - Use `map()` to map the values of the given list using the given function. - Iterate over the map and increase the element count each time it occurs. ```py from collections import defaultdict def count_by(lst, fn = lambda x: x): count = defaultdict(int) for val in map(fn, lst): count[val] += 1 return dict(count) ``` ```py from math import floor count_by([6.1, 4.2, 6.3], floor) # {6: 2, 4: 1} count_by(['one', 'two', 'three'], len) # {3: 2, 5: 1} ``` ================================================ FILE: snippets/count-occurrences.md ================================================ --- title: Count occurrences type: snippet tags: [list] cover: pineapple-at-work dateModified: 2021-01-10T00:00:36+02:00 --- Counts the occurrences of a value in a list. - Use `list.count()` to count the number of occurrences of `val` in `lst`. ```py def count_occurrences(lst, val): return lst.count(val) ``` ```py count_occurrences([1, 1, 2, 1, 2, 3], 1) # 3 ``` ================================================ FILE: snippets/cumsum.md ================================================ --- title: Partial sum list type: snippet tags: [list] cover: digital-nomad-16 dateModified: 2021-01-13T23:30:41+02:00 --- Creates a list of partial sums. - Use `itertools.accumulate()` to create the accumulated sum for each element. - Use `list()` to convert the result into a list. ```py from itertools import accumulate def cumsum(lst): return list(accumulate(lst)) ``` ```py cumsum(range(0, 15, 3)) # [0, 3, 9, 18, 30] ``` ================================================ FILE: snippets/curry.md ================================================ --- title: Curry function type: snippet tags: [function] cover: leaves-read dateModified: 2020-11-02T19:27:07+02:00 --- Curries a function. - Use `functools.partial()` to return a new partial object which behaves like `fn` with the given arguments, `args`, partially applied. ```py from functools import partial def curry(fn, *args): return partial(fn, *args) ``` ```py add = lambda x, y: x + y add10 = curry(add, 10) add10(20) # 30 ``` ================================================ FILE: snippets/daterange.md ================================================ --- title: Date range type: snippet tags: [date] cover: maple-leaf-palette dateModified: 2021-01-07T23:30:28+02:00 --- Creates a list of dates between `start` (inclusive) and `end` (not inclusive). - Use `datetime.timedelta.days` to get the days between `start` and `end`. - Use `int()` to convert the result to an integer and `range()` to iterate over each day. - Use a list comprehension and `datetime.timedelta` to create a list of `datetime.date` objects. ```py from datetime import timedelta, date def daterange(start, end): return [start + timedelta(n) for n in range(int((end - start).days))] ``` ```py from datetime import date daterange(date(2020, 10, 1), date(2020, 10, 5)) # [date(2020, 10, 1), date(2020, 10, 2), date(2020, 10, 3), date(2020, 10, 4)] ``` ================================================ FILE: snippets/days-ago.md ================================================ --- title: Days ago type: snippet tags: [date] cover: cup-of-orange dateModified: 2020-10-28T16:19:30+02:00 --- Calculates the date of `n` days ago from today. - Use `datetime.date.today()` to get the current day. - Use `datetime.timedelta` to subtract `n` days from today's date. ```py from datetime import timedelta, date def days_ago(n): return date.today() - timedelta(n) ``` ```py days_ago(5) # date(2020, 10, 23) ``` ================================================ FILE: snippets/days-diff.md ================================================ --- title: Date difference in days type: snippet tags: [date] cover: succulent-9 dateModified: 2020-10-28T16:19:39+02:00 --- Calculates the day difference between two dates. - Subtract `start` from `end` and use `datetime.timedelta.days` to get the day difference. ```py def days_diff(start, end): return (end - start).days ``` ```py from datetime import date days_diff(date(2020, 10, 25), date(2020, 10, 28)) # 3 ``` ================================================ FILE: snippets/days-from-now.md ================================================ --- title: Days from now type: snippet tags: [date] cover: clutter dateModified: 2020-10-28T16:19:51+02:00 --- Calculates the date of `n` days from today. - Use `datetime.date.today()` to get the current day. - Use `datetime.timedelta` to add `n` days from today's date. ```py from datetime import timedelta, date def days_from_now(n): return date.today() + timedelta(n) ``` ```py days_from_now(5) # date(2020, 11, 02) ``` ================================================ FILE: snippets/decapitalize.md ================================================ --- title: Decapitalize string type: snippet tags: [string] cover: succulent-crowd dateModified: 2020-11-02T19:27:53+02:00 --- Decapitalizes the first letter of a string. - Use list slicing and `str.lower()` to decapitalize the first letter of the string. - Use `str.join()` to combine the lowercase first letter with the rest of the characters. - Omit the `upper_rest` parameter to keep the rest of the string intact, or set it to `True` to convert to uppercase. ```py def decapitalize(s, upper_rest = False): return ''.join([s[:1].lower(), (s[1:].upper() if upper_rest else s[1:])]) ``` ```py decapitalize('FooBar') # 'fooBar' decapitalize('FooBar', True) # 'fOOBAR' ``` ================================================ FILE: snippets/deep-flatten.md ================================================ --- title: Deep flatten list type: snippet tags: [list,recursion] cover: mask-quiet dateModified: 2020-12-29T19:53:45+02:00 --- Deep flattens a list. - Use recursion. - Use `isinstance()` with `collections.abc.Iterable` to check if an element is iterable. - If it is iterable, apply `deep_flatten()` recursively, otherwise return `[lst]`. ```py from collections.abc import Iterable def deep_flatten(lst): return ([a for i in lst for a in deep_flatten(i)] if isinstance(lst, Iterable) else [lst]) ``` ```py deep_flatten([1, [2], [[3], 4], 5]) # [1, 2, 3, 4, 5] ``` ================================================ FILE: snippets/degrees-to-rads.md ================================================ --- title: Degrees to radians type: snippet tags: [math] cover: digital-nomad-6 dateModified: 2020-11-02T19:27:53+02:00 --- Converts an angle from degrees to radians. - Use `math.pi` and the degrees to radians formula to convert the angle from degrees to radians. ```py from math import pi def degrees_to_rads(deg): return (deg * pi) / 180.0 ``` ```py degrees_to_rads(180) # ~3.1416 ``` ================================================ FILE: snippets/delay.md ================================================ --- title: Delayed function execution type: snippet tags: [function] cover: succulent-10 dateModified: 2020-11-02T19:27:53+02:00 --- Invokes the provided function after `ms` milliseconds. - Use `time.sleep()` to delay the execution of `fn` by `ms / 1000` seconds. ```py from time import sleep def delay(fn, ms, *args): sleep(ms / 1000) return fn(*args) ``` ```py delay(lambda x: print(x), 1000, 'later') # prints 'later' after one second ``` ================================================ FILE: snippets/dict-to-list.md ================================================ --- title: Dictionary to list type: snippet tags: [dictionary,list] cover: new-york dateModified: 2020-11-02T19:27:53+02:00 --- Converts a dictionary to a list of tuples. - Use `dict.items()` and `list()` to get a list of tuples from the given dictionary. ```py def dict_to_list(d): return list(d.items()) ``` ```py d = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4} dict_to_list(d) # [('one', 1), ('three', 3), ('five', 5), ('two', 2), ('four', 4)] ``` ================================================ FILE: snippets/difference-by.md ================================================ --- title: List difference based on function type: snippet tags: [list,function] cover: coconuts dateModified: 2020-11-02T19:27:53+02:00 --- Returns the difference between two lists, after applying the provided function to each list element of both. - Create a `set`, using `map()` to apply `fn` to each element in `b`. - Use a list comprehension in combination with `fn` on `a` to only keep values not contained in the previously created set, `_b`. ```py def difference_by(a, b, fn): _b = set(map(fn, b)) return [item for item in a if fn(item) not in _b] ``` ```py from math import floor difference_by([2.1, 1.2], [2.3, 3.4], floor) # [1.2] difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ] ``` ================================================ FILE: snippets/difference.md ================================================ --- title: List difference type: snippet tags: [list] cover: frog-blue-flower dateModified: 2020-11-02T19:27:53+02:00 --- Calculates the difference between two iterables, without filtering duplicate values. - Create a `set` from `b`. - Use a list comprehension on `a` to only keep values not contained in the previously created set, `_b`. ```py def difference(a, b): _b = set(b) return [item for item in a if item not in _b] ``` ```py difference([1, 2, 3], [1, 2, 4]) # [3] ``` ================================================ FILE: snippets/digitize.md ================================================ --- title: Digitize number type: snippet tags: [math,list] cover: laptop-with-code dateModified: 2020-09-15T16:13:06+03:00 --- Converts a number to a list of digits. - Use `map()` combined with `int` on the string representation of `n` and return a list from the result. ```py def digitize(n): return list(map(int, str(n))) ``` ```py digitize(123) # [1, 2, 3] ``` ================================================ FILE: snippets/drop-right.md ================================================ --- title: Drop list elements from the right type: snippet tags: [list] author: chalarangelo cover: digital-nomad-7 dateModified: 2020-11-02T19:27:53+02:00 --- Returns a list with `n` elements removed from the right. - Use slice notation to remove the specified number of elements from the right. - Omit the last argument, `n`, to use a default value of `1`. ```py def drop_right(a, n = 1): return a[:-n] ``` ```py drop_right([1, 2, 3]) # [1, 2] drop_right([1, 2, 3], 2) # [1] drop_right([1, 2, 3], 42) # [] ``` ================================================ FILE: snippets/drop.md ================================================ --- title: Drop list elements from the left type: snippet tags: [list] author: chalarangelo cover: pink-flower dateModified: 2020-11-02T19:27:53+02:00 --- Returns a list with `n` elements removed from the left. - Use slice notation to remove the specified number of elements from the left. - Omit the last argument, `n`, to use a default value of `1`. ```py def drop(a, n = 1): return a[n:] ``` ```py drop([1, 2, 3]) # [2, 3] drop([1, 2, 3], 2) # [3] drop([1, 2, 3], 42) # [] ``` ================================================ FILE: snippets/every-nth.md ================================================ --- title: Every nth element in list type: snippet tags: [list] cover: cherry-trees dateModified: 2020-11-02T19:27:53+02:00 --- Returns every `nth` element in a list. - Use slice notation to create a new list that contains every `nth` element of the given list. ```py def every_nth(lst, nth): return lst[nth - 1::nth] ``` ```py every_nth([1, 2, 3, 4, 5, 6], 2) # [ 2, 4, 6 ] ``` ================================================ FILE: snippets/every.md ================================================ --- title: Test if every list element is truthy type: snippet tags: [list] cover: walking dateModified: 2020-11-02T19:27:53+02:00 --- Checks if the provided function returns `True` for every element in the list. - Use `all()` in combination with `map()` and `fn` to check if `fn` returns `True` for all elements in the list. ```py def every(lst, fn = lambda x: x): return all(map(fn, lst)) ``` ```py every([4, 2, 3], lambda x: x > 1) # True every([1, 2, 3]) # True ``` ================================================ FILE: snippets/factorial.md ================================================ --- title: Factorial type: snippet tags: [math,recursion] cover: succulent-11 dateModified: 2020-09-15T16:13:06+03:00 --- Calculates the factorial of a number. - Use recursion. - If `num` is less than or equal to `1`, return `1`. - Otherwise, return the product of `num` and the factorial of `num - 1`. - Throws an exception if `num` is a negative or a floating point number. ```py def factorial(num): if not ((num >= 0) and (num % 1 == 0)): raise Exception("Number can't be floating point or negative.") return 1 if num == 0 else num * factorial(num - 1) ``` ```py factorial(6) # 720 ``` ================================================ FILE: snippets/fahrenheit-to-celsius.md ================================================ --- title: Fahrenheit to Celsius type: snippet tags: [math] unlisted: true cover: last-light dateModified: 2021-01-04T12:47:04+02:00 --- Converts Fahrenheit to Celsius. - Follow the conversion formula `C = (F - 32) * 5 / 9`. ```py def fahrenheit_to_celsius(degrees): return ((degrees - 32) * 5 / 9) ``` ```py fahrenheit_to_celsius(77) # 25.0 ``` ================================================ FILE: snippets/fibonacci.md ================================================ --- title: Fibonacci type: snippet tags: [math,list] cover: san-francisco-skyline dateModified: 2020-11-02T19:27:53+02:00 --- Generates a list, containing the Fibonacci sequence, up until the nth term. - Starting with `0` and `1`, use `list.append()` to add the sum of the last two numbers of the list to the end of the list, until the length of the list reaches `n`. - If `n` is less or equal to `0`, return a list containing `0`. ```py def fibonacci(n): if n <= 0: return [0] sequence = [0, 1] while len(sequence) <= n: next_value = sequence[len(sequence) - 1] + sequence[len(sequence) - 2] sequence.append(next_value) return sequence ``` ```py fibonacci(7) # [0, 1, 1, 2, 3, 5, 8, 13] ``` ================================================ FILE: snippets/filter-non-unique.md ================================================ --- title: Filter non-unique list values type: snippet tags: [list] cover: cobbled-street dateModified: 2020-11-02T19:27:53+02:00 --- Creates a list with the non-unique values filtered out. - Use `collections.Counter` to get the count of each value in the list. - Use a list comprehension to create a list containing only the unique values. ```py from collections import Counter def filter_non_unique(lst): return [item for item, count in Counter(lst).items() if count == 1] ``` ```py filter_non_unique([1, 2, 2, 3, 4, 4, 5]) # [1, 3, 5] ``` ================================================ FILE: snippets/filter-unique.md ================================================ --- title: Filter unique list values type: snippet tags: [list] cover: feathers dateModified: 2020-11-02T19:27:53+02:00 --- Creates a list with the unique values filtered out. - Use `collections.Counter` to get the count of each value in the list. - Use a list comprehension to create a list containing only the non-unique values. ```py from collections import Counter def filter_unique(lst): return [item for item, count in Counter(lst).items() if count > 1] ``` ```py filter_unique([1, 2, 2, 3, 4, 4, 5]) # [2, 4] ``` ================================================ FILE: snippets/find-index-of-all.md ================================================ --- title: Find all matching indexes type: snippet tags: [list] cover: tree-roots dateModified: 2020-11-02T19:27:53+02:00 --- Finds the indexes of all elements in the given list that satisfy the provided testing function. - Use `enumerate()` and a list comprehension to return the indexes of the all element in `lst` for which `fn` returns `True`. ```py def find_index_of_all(lst, fn): return [i for i, x in enumerate(lst) if fn(x)] ``` ```py find_index_of_all([1, 2, 3, 4], lambda n: n % 2 == 1) # [0, 2] ``` ================================================ FILE: snippets/find-index.md ================================================ --- title: Find matching index type: snippet tags: [list] cover: book-chair dateModified: 2020-11-02T19:27:53+02:00 --- Finds the index of the first element in the given list that satisfies the provided testing function. - Use a list comprehension, `enumerate()` and `next()` to return the index of the first element in `lst` for which `fn` returns `True`. ```py def find_index(lst, fn): return next(i for i, x in enumerate(lst) if fn(x)) ``` ```py find_index([1, 2, 3, 4], lambda n: n % 2 == 1) # 0 ``` ================================================ FILE: snippets/find-key.md ================================================ --- title: Find key of value type: snippet tags: [dictionary] cover: blue-red-mountain dateModified: 2020-11-02T19:27:53+02:00 --- Finds the first key in the provided dictionary that has the given value. - Use `dictionary.items()` and `next()` to return the first key that has a value equal to `val`. ```py def find_key(dict, val): return next(key for key, value in dict.items() if value == val) ``` ```py ages = { 'Peter': 10, 'Isabel': 11, 'Anna': 9, } find_key(ages, 11) # 'Isabel' ``` ================================================ FILE: snippets/find-keys.md ================================================ --- title: Find keys with value type: snippet tags: [dictionary] cover: laptop-plants-2 dateModified: 2020-11-02T19:27:53+02:00 --- Finds all keys in the provided dictionary that have the given value. - Use `dictionary.items()`, a generator and `list()` to return all keys that have a value equal to `val`. ```py def find_keys(dict, val): return list(key for key, value in dict.items() if value == val) ``` ```py ages = { 'Peter': 10, 'Isabel': 11, 'Anna': 10, } find_keys(ages, 10) # [ 'Peter', 'Anna' ] ``` ================================================ FILE: snippets/find-last-index.md ================================================ --- title: Find last matching index type: snippet tags: [list] cover: succulent-8 dateModified: 2020-11-02T19:27:53+02:00 --- Finds the index of the last element in the given list that satisfies the provided testing function. - Use a list comprehension, `enumerate()` and `next()` to return the index of the last element in `lst` for which `fn` returns `True`. ```py def find_last_index(lst, fn): return len(lst) - 1 - next(i for i, x in enumerate(lst[::-1]) if fn(x)) ``` ```py find_last_index([1, 2, 3, 4], lambda n: n % 2 == 1) # 2 ``` ================================================ FILE: snippets/find-last.md ================================================ --- title: Find last matching value type: snippet tags: [list] cover: tropical-waterfall dateModified: 2020-11-02T19:27:53+02:00 --- Finds the value of the last element in the given list that satisfies the provided testing function. - Use a list comprehension and `next()` to return the last element in `lst` for which `fn` returns `True`. ```py def find_last(lst, fn): return next(x for x in lst[::-1] if fn(x)) ``` ```py find_last([1, 2, 3, 4], lambda n: n % 2 == 1) # 3 ``` ================================================ FILE: snippets/find-parity-outliers.md ================================================ --- title: Find parity outliers type: snippet tags: [list,math] cover: beach-pineapple dateModified: 2020-11-02T19:27:53+02:00 --- Finds the items that are parity outliers in a given list. - Use `collections.Counter` with a list comprehension to count even and odd values in the list. - Use `collections.Counter.most_common()` to get the most common parity. - Use a list comprehension to find all elements that do not match the most common parity. ```py from collections import Counter def find_parity_outliers(nums): return [ x for x in nums if x % 2 != Counter([n % 2 for n in nums]).most_common()[0][0] ] ``` ```py find_parity_outliers([1, 2, 3, 4, 6]) # [1, 3] ``` ================================================ FILE: snippets/find.md ================================================ --- title: Find matching value type: snippet tags: [list] cover: duck-plants dateModified: 2020-11-02T19:27:53+02:00 --- Finds the value of the first element in the given list that satisfies the provided testing function. - Use a list comprehension and `next()` to return the first element in `lst` for which `fn` returns `True`. ```py def find(lst, fn): return next(x for x in lst if fn(x)) ``` ```py find([1, 2, 3, 4], lambda n: n % 2 == 1) # 1 ``` ================================================ FILE: snippets/flatten.md ================================================ --- title: Flatten list type: snippet tags: [list] cover: jars-on-shelf dateModified: 2020-11-02T19:27:53+02:00 --- Flattens a list of lists once. - Use a list comprehension to extract each value from sub-lists in order. ```py def flatten(lst): return [x for y in lst for x in y] ``` ```py flatten([[1, 2, 3, 4], [5, 6, 7, 8]]) # [1, 2, 3, 4, 5, 6, 7, 8] ``` ================================================ FILE: snippets/for-each-right.md ================================================ --- title: Execute function for each list element in reverse type: snippet tags: [list] cover: bridge-drop dateModified: 2020-09-15T16:13:06+03:00 --- Executes the provided function once for each list element, starting from the list's last element. - Use a `for` loop in combination with slice notation to execute `fn` for each element in `itr`, starting from the last one. ```py def for_each_right(itr, fn): for el in itr[::-1]: fn(el) ``` ```py for_each_right([1, 2, 3], print) # 3 2 1 ``` ================================================ FILE: snippets/for-each.md ================================================ --- title: Execute function for each list element type: snippet tags: [list] cover: green-plant dateModified: 2020-09-15T16:13:06+03:00 --- Executes the provided function once for each list element. - Use a `for` loop to execute `fn` for each element in `itr`. ```py def for_each(itr, fn): for el in itr: fn(el) ``` ```py for_each([1, 2, 3], print) # 1 2 3 ``` ================================================ FILE: snippets/frequencies.md ================================================ --- title: Value frequencies type: snippet tags: [list] cover: succulent-6 dateModified: 2020-11-02T19:27:53+02:00 --- Creates a dictionary with the unique values of a list as keys and their frequencies as the values. - Use `collections.defaultdict` to store the frequencies of each unique element. - Use `dict()` to return a dictionary with the unique elements of the list as keys and their frequencies as the values. ```py from collections import defaultdict def frequencies(lst): freq = defaultdict(int) for val in lst: freq[val] += 1 return dict(freq) ``` ```py frequencies(['a', 'b', 'a', 'c', 'a', 'a', 'b']) # { 'a': 4, 'b': 2, 'c': 1 } ``` ================================================ FILE: snippets/from-iso-date.md ================================================ --- title: Date from ISO format type: snippet tags: [date] cover: purple-leaves dateModified: 2021-01-07T23:30:28+02:00 --- Converts a date from its ISO-8601 representation. - Use `datetime.datetime.fromisoformat()` to convert the given ISO-8601 date to a `datetime.datetime` object. ```py from datetime import datetime def from_iso_date(d): return datetime.fromisoformat(d) ``` ```py from_iso_date('2020-10-28T12:30:59.000000') # 2020-10-28 12:30:59 ``` ================================================ FILE: snippets/gcd.md ================================================ --- title: Greatest common divisor type: snippet tags: [math] cover: digital-nomad-12 dateModified: 2020-09-15T16:13:06+03:00 --- Calculates the greatest common divisor of a list of numbers. - Use `functools.reduce()` and `math.gcd()` over the given list. ```py from functools import reduce from math import gcd as _gcd def gcd(numbers): return reduce(_gcd, numbers) ``` ```py gcd([8, 36, 28]) # 4 ``` ================================================ FILE: snippets/geometric-progression.md ================================================ --- title: Geometric progression type: snippet tags: [math,list] cover: kettle-laptop excerpt: Initializes a list containing the numbers in the specified geometric progression range. dateModified: 2020-11-02T19:28:05+02:00 --- Initializes a list containing the numbers in the specified range where `start` and `end` are inclusive and the ratio between two terms is `step`. - Use `range()`, `math.log()` and `math.floor()` and a list comprehension to create a list of the appropriate length, applying the step for each element. - Returns an error if `step` equals `1`. - Omit the second argument, `start`, to use a default value of `1`. - Omit the third argument, `step`, to use a default value of `2`. ```py from math import floor, log def geometric_progression(end, start=1, step=2): return [start * step ** i for i in range(floor(log(end / start) / log(step)) + 1)] ``` ```py geometric_progression(256) # [1, 2, 4, 8, 16, 32, 64, 128, 256] geometric_progression(256, 3) # [3, 6, 12, 24, 48, 96, 192] geometric_progression(256, 1, 4) # [1, 4, 16, 64, 256] ``` ================================================ FILE: snippets/get.md ================================================ --- title: Get nested value type: snippet tags: [dictionary,list] cover: digital-nomad-2 dateModified: 2020-10-28T12:21:39+02:00 --- Retrieves the value of the nested key indicated by the given selector list from a dictionary or list. - Use `functools.reduce()` to iterate over the `selectors` list. - Apply `operator.getitem()` for each key in `selectors`, retrieving the value to be used as the iteratee for the next iteration. ```py from functools import reduce from operator import getitem def get(d, selectors): return reduce(getitem, selectors, d) ``` ```py users = { 'freddy': { 'name': { 'first': 'fred', 'last': 'smith' }, 'postIds': [1, 2, 3] } } get(users, ['freddy', 'name', 'last']) # 'smith' get(users, ['freddy', 'postIds', 1]) # 2 ``` ================================================ FILE: snippets/group-by.md ================================================ --- title: Group list elements type: snippet tags: [list,dictionary] cover: body-of-water dateModified: 2020-11-02T19:28:05+02:00 --- Groups the elements of a list based on the given function. - Use `collections.defaultdict` to initialize a dictionary. - Use `fn` in combination with a `for` loop and `dict.append()` to populate the dictionary. - Use `dict()` to convert it to a regular dictionary. ```py from collections import defaultdict def group_by(lst, fn): d = defaultdict(list) for el in lst: d[fn(el)].append(el) return dict(d) ``` ```py from math import floor group_by([6.1, 4.2, 6.3], floor) # {4: [4.2], 6: [6.1, 6.3]} group_by(['one', 'two', 'three'], len) # {3: ['one', 'two'], 5: ['three']} ``` ================================================ FILE: snippets/hamming-distance.md ================================================ --- title: Hamming distance type: snippet tags: [math] cover: tulips-and-reeds dateModified: 2021-02-18T14:22:25+02:00 --- Calculates the Hamming distance between two values. - Use the XOR operator (`^`) to find the bit difference between the two numbers. - Use `bin()` to convert the result to a binary string. - Convert the string to a list and use `count()` of `str` class to count and return the number of `1`s in it. ```py def hamming_distance(a, b): return bin(a ^ b).count('1') ``` ```py hamming_distance(2, 3) # 1 ``` ================================================ FILE: snippets/has-duplicates.md ================================================ --- title: Check for duplicates in list type: snippet tags: [list] cover: jars-on-shelf-2 dateModified: 2020-11-02T19:28:05+02:00 --- Checks if there are duplicate values in a flat list. - Use `set()` on the given list to remove duplicates, compare its length with the length of the list. ```py def has_duplicates(lst): return len(lst) != len(set(lst)) ``` ```py x = [1, 2, 3, 4, 5, 5] y = [1, 2, 3, 4, 5] has_duplicates(x) # True has_duplicates(y) # False ``` ================================================ FILE: snippets/have-same-contents.md ================================================ --- title: Check lists have same contents type: snippet tags: [list] cover: racoon dateModified: 2020-11-02T19:28:05+02:00 --- Checks if two lists contain the same elements regardless of order. - Use `set()` on the combination of both lists to find the unique values. - Iterate over them with a `for` loop comparing the `count()` of each unique value in each list. - Return `False` if the counts do not match for any element, `True` otherwise. ```py def have_same_contents(a, b): for v in set(a + b): if a.count(v) != b.count(v): return False return True ``` ```py have_same_contents([1, 2, 4], [2, 4, 1]) # True ``` ================================================ FILE: snippets/head.md ================================================ --- title: List head type: snippet tags: [list] cover: purple-laptop dateModified: 2020-09-15T16:13:06+03:00 --- Returns the head of a list. - Use `lst[0]` to return the first element of the passed list. ```py def head(lst): return lst[0] ``` ```py head([1, 2, 3]) # 1 ``` ================================================ FILE: snippets/hex-to-rgb.md ================================================ --- title: Hex to RGB type: snippet tags: [string,math] cover: sleepy-cat dateModified: 2020-09-15T16:13:06+03:00 --- Converts a hexadecimal color code to a tuple of integers corresponding to its RGB components. - Use a list comprehension in combination with `int()` and list slice notation to get the RGB components from the hexadecimal string. - Use `tuple()` to convert the resulting list to a tuple. ```py def hex_to_rgb(hex): return tuple(int(hex[i:i+2], 16) for i in (0, 2, 4)) ``` ```py hex_to_rgb('FFA501') # (255, 165, 1) ``` ================================================ FILE: snippets/in-range.md ================================================ --- title: Number in range type: snippet tags: [math] cover: pineapple-on-green dateModified: 2020-09-15T16:13:06+03:00 --- Checks if the given number falls within the given range. - Use arithmetic comparison to check if the given number is in the specified range. - If the second parameter, `end`, is not specified, the range is considered to be from `0` to `start`. ```py def in_range(n, start, end = 0): return start <= n <= end if end >= start else end <= n <= start ``` ```py in_range(3, 2, 5) # True in_range(3, 4) # True in_range(2, 3, 5) # False in_range(3, 2) # False ``` ================================================ FILE: snippets/includes-all.md ================================================ --- title: List includes all values type: snippet tags: [list] cover: switzerland-night dateModified: 2020-11-02T19:28:05+02:00 --- Checks if all the elements in `values` are included in `lst`. - Check if every value in `values` is contained in `lst` using a `for` loop. - Return `False` if any one value is not found, `True` otherwise. ```py def includes_all(lst, values): for v in values: if v not in lst: return False return True ``` ```py includes_all([1, 2, 3, 4], [1, 4]) # True includes_all([1, 2, 3, 4], [1, 5]) # False ``` ================================================ FILE: snippets/includes-any.md ================================================ --- title: List includes any values type: snippet tags: [list] cover: forest-balcony dateModified: 2020-11-02T19:28:05+02:00 --- Checks if any element in `values` is included in `lst`. - Check if any value in `values` is contained in `lst` using a `for` loop. - Return `True` if any one value is found, `False` otherwise. ```py def includes_any(lst, values): for v in values: if v in lst: return True return False ``` ```py includes_any([1, 2, 3, 4], [2, 9]) # True includes_any([1, 2, 3, 4], [8, 9]) # False ``` ================================================ FILE: snippets/index-of-all.md ================================================ --- title: All indexes of value type: snippet tags: [list] cover: purple-flower-bunch dateModified: 2020-10-11T13:45:19+03:00 --- Returns a list of indexes of all the occurrences of an element in a list. - Use `enumerate()` and a list comprehension to check each element for equality with `value` and adding `i` to the result. ```py def index_of_all(lst, value): return [i for i, x in enumerate(lst) if x == value] ``` ```py index_of_all([1, 2, 1, 4, 5, 1], 1) # [0, 2, 5] index_of_all([1, 2, 3, 4], 6) # [] ``` ================================================ FILE: snippets/initial.md ================================================ --- title: List without last element type: snippet tags: [list] cover: pop-of-green dateModified: 2020-11-02T19:28:05+02:00 --- Returns all the elements of a list except the last one. - Use `lst[:-1]` to return all but the last element of the list. ```py def initial(lst): return lst[:-1] ``` ```py initial([1, 2, 3]) # [1, 2] ``` ================================================ FILE: snippets/initialize-2-d-list.md ================================================ --- title: Initialize 2D list type: snippet tags: [list] cover: succulent-7 dateModified: 2020-11-02T19:28:05+02:00 --- Initializes a 2D list of given width and height and value. - Use a list comprehension and `range()` to generate `h` rows where each is a list with length `h`, initialized with `val`. - Omit the last argument, `val`, to set the default value to `None`. ```py def initialize_2d_list(w, h, val = None): return [[val for x in range(w)] for y in range(h)] ``` ```py initialize_2d_list(2, 2, 0) # [[0, 0], [0, 0]] ``` ================================================ FILE: snippets/initialize-list-with-range.md ================================================ --- title: Initialize list with range type: snippet tags: [list] cover: succulent-3 dateModified: 2020-11-02T19:28:05+02:00 --- Initializes a list containing the numbers in the specified range where `start` and `end` are inclusive with their common difference `step`. - Use `list()` and `range()` to generate a list of the appropriate length, filled with the desired values in the given range. - Omit `start` to use the default value of `0`. - Omit `step` to use the default value of `1`. ```py def initialize_list_with_range(end, start = 0, step = 1): return list(range(start, end + 1, step)) ``` ```py initialize_list_with_range(5) # [0, 1, 2, 3, 4, 5] initialize_list_with_range(7, 3) # [3, 4, 5, 6, 7] initialize_list_with_range(9, 0, 2) # [0, 2, 4, 6, 8] ``` ================================================ FILE: snippets/initialize-list-with-values.md ================================================ --- title: Initialize list with values type: snippet tags: [list] cover: dog-waiting dateModified: 2020-11-02T19:28:05+02:00 --- Initializes and fills a list with the specified value. - Use a list comprehension and `range()` to generate a list of length equal to `n`, filled with the desired values. - Omit `val` to use the default value of `0`. ```py def initialize_list_with_values(n, val = 0): return [val for x in range(n)] ``` ```py initialize_list_with_values(5, 2) # [2, 2, 2, 2, 2] ``` ================================================ FILE: snippets/intersection-by.md ================================================ --- title: List intersection based on function type: snippet tags: [list,function] cover: duck-plants dateModified: 2020-11-02T19:28:05+02:00 --- Returns a list of elements that exist in both lists, after applying the provided function to each list element of both. - Create a `set`, using `map()` to apply `fn` to each element in `b`. - Use a list comprehension in combination with `fn` on `a` to only keep values contained in both lists. ```py def intersection_by(a, b, fn): _b = set(map(fn, b)) return [item for item in a if fn(item) in _b] ``` ```py from math import floor intersection_by([2.1, 1.2], [2.3, 3.4], floor) # [2.1] ``` ================================================ FILE: snippets/intersection.md ================================================ --- title: List intersection type: snippet tags: [list] cover: wooden-bowl dateModified: 2020-11-02T19:28:05+02:00 --- Returns a list of elements that exist in both lists. - Create a `set` from `a` and `b`. - Use the built-in set operator `&` to only keep values contained in both sets, then transform the `set` back into a `list`. ```py def intersection(a, b): _a, _b = set(a), set(b) return list(_a & _b) ``` ```py intersection([1, 2, 3], [4, 3, 2]) # [2, 3] ``` ================================================ FILE: snippets/invert-dictionary.md ================================================ --- title: Invert dictionary type: snippet tags: [dictionary] cover: rustic-cup dateModified: 2020-11-02T19:28:05+02:00 --- Inverts a dictionary with unique hashable values. - Use `dictionary.items()` in combination with a list comprehension to create a new dictionary with the values and keys inverted. ```py def invert_dictionary(obj): return { value: key for key, value in obj.items() } ``` ```py ages = { 'Peter': 10, 'Isabel': 11, 'Anna': 9, } invert_dictionary(ages) # { 10: 'Peter', 11: 'Isabel', 9: 'Anna' } ``` ================================================ FILE: snippets/is-anagram.md ================================================ --- title: String is anagram type: snippet tags: [string] cover: digital-nomad-8 dateModified: 2020-11-02T19:28:05+02:00 --- Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters). - Use `str.isalnum()` to filter out non-alphanumeric characters, `str.lower()` to transform each character to lowercase. - Use `collections.Counter` to count the resulting characters for each string and compare the results. ```py from collections import Counter def is_anagram(s1, s2): return Counter( c.lower() for c in s1 if c.isalnum() ) == Counter( c.lower() for c in s2 if c.isalnum() ) ``` ```py is_anagram('#anagram', 'Nag a ram!') # True ``` ================================================ FILE: snippets/is-contained-in.md ================================================ --- title: List is contained in other list type: snippet tags: [list] cover: tropical-bike dateModified: 2021-01-07T23:30:28+02:00 --- Checks if the elements of the first list are contained in the second one regardless of order. - Use `count()` to check if any value in `a` has more occurrences than it has in `b`. - Return `False` if any such value is found, `True` otherwise. ```py def is_contained_in(a, b): for v in set(a): if a.count(v) > b.count(v): return False return True ``` ```py is_contained_in([1, 4], [2, 4, 1]) # True ``` ================================================ FILE: snippets/is-divisible.md ================================================ --- title: Number is divisible type: snippet tags: [math] unlisted: true cover: interior-9 dateModified: 2021-01-04T12:47:04+02:00 --- Checks if the first numeric argument is divisible by the second one. - Use the modulo operator (`%`) to check if the remainder is equal to `0`. ```py def is_divisible(dividend, divisor): return dividend % divisor == 0 ``` ```py is_divisible(6, 3) # True ``` ================================================ FILE: snippets/is-empty.md ================================================ --- title: Collection is empty type: snippet tags: [list,dictionary,string] author: chalarangelo cover: salad-1 dateModified: 2023-01-12T05:00:00-04:00 --- Checks if the a value is an empty sequence or collection. - Use `not` to test the truth value of the provided sequence or collection. ```py def is_empty(val): return not val ``` ```py is_empty([]) # True is_empty({}) # True is_empty('') # True is_empty(set()) # True is_empty(range(0)) # True is_empty([1, 2]) # False is_empty({ 'a': 1, 'b': 2 }) # False is_empty('text') # False is_empty(set([1, 2])) # False is_empty(range(2)) # False ``` ================================================ FILE: snippets/is-even.md ================================================ --- title: Number is even type: snippet tags: [math] unlisted: true cover: interior-3 dateModified: 2021-01-04T12:47:04+02:00 --- Checks if the given number is even. - Check whether a number is odd or even using the modulo (`%`) operator. - Return `True` if the number is even, `False` if the number is odd. ```py def is_even(num): return num % 2 == 0 ``` ```py is_even(3) # False ``` ================================================ FILE: snippets/is-odd.md ================================================ --- title: Number is odd type: snippet tags: [math] unlisted: true cover: interior-6 dateModified: 2021-01-04T12:47:04+02:00 --- Checks if the given number is odd. - Checks whether a number is even or odd using the modulo (`%`) operator. - Returns `True` if the number is odd, `False` if the number is even. ```py def is_odd(num): return num % 2 != 0 ``` ```py is_odd(3) # True ``` ================================================ FILE: snippets/is-prime.md ================================================ --- title: Number is prime type: snippet tags: [math] cover: carrots dateModified: 2020-11-02T19:28:05+02:00 --- Checks if the provided integer is a prime number. - Return `False` if the number is `0`, `1`, a negative number or a multiple of `2`. - Use `all()` and `range()` to check numbers from `3` to the square root of the given number. - Return `True` if none divides the given number, `False` otherwise. ```py from math import sqrt def is_prime(n): if n <= 1 or (n % 2 == 0 and n > 2): return False return all(n % i for i in range(3, int(sqrt(n)) + 1, 2)) ``` ```py is_prime(11) # True ``` ================================================ FILE: snippets/is-weekday.md ================================================ --- title: Date is weekday type: snippet tags: [date] cover: succulent-4 dateModified: 2020-11-02T19:28:05+02:00 --- Checks if the given date is a weekday. - Use `datetime.datetime.weekday()` to get the day of the week as an integer. - Check if the day of the week is less than or equal to `4`. - Omit the second argument, `d`, to use a default value of `datetime.today()`. ```py from datetime import datetime def is_weekday(d = datetime.today()): return d.weekday() <= 4 ``` ```py from datetime import date is_weekday(date(2020, 10, 25)) # False is_weekday(date(2020, 10, 28)) # True ``` ================================================ FILE: snippets/is-weekend.md ================================================ --- title: Date is weekend type: snippet tags: [date] cover: two-lighthouses dateModified: 2020-11-02T19:28:05+02:00 --- Checks if the given date is a weekend. - Use `datetime.datetime.weekday()` to get the day of the week as an integer. - Check if the day of the week is greater than `4`. - Omit the second argument, `d`, to use a default value of `datetime.today()`. ```py from datetime import datetime def is_weekend(d = datetime.today()): return d.weekday() > 4 ``` ```py from datetime import date is_weekend(date(2020, 10, 25)) # True is_weekend(date(2020, 10, 28)) # False ``` ================================================ FILE: snippets/kebab.md ================================================ --- title: Kebabcase string type: snippet tags: [string,regexp] cover: mask-quiet dateModified: 2020-11-02T19:28:05+02:00 --- Converts a string to kebab case. - Use `re.sub()` to replace any `-` or `_` with a space, using the regexp `r"(_|-)+"`. - Use `re.sub()` to match all words in the string, `str.lower()` to lowercase them. - Finally, use `str.join()` to combine all word using `-` as the separator. ```py from re import sub def kebab(s): return '-'.join( sub(r"(\s|_|-)+"," ", sub(r"[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+", lambda mo: ' ' + mo.group(0).lower(), s)).split()) ``` ```py kebab('camelCase') # 'camel-case' kebab('some text') # 'some-text' kebab('some-mixed_string With spaces_underscores-and-hyphens') # 'some-mixed-string-with-spaces-underscores-and-hyphens' kebab('AllThe-small Things') # 'all-the-small-things' ``` ================================================ FILE: snippets/key-in-dict.md ================================================ --- title: Key in dictionary type: snippet tags: [dictionary] cover: rocky-mountains dateModified: 2020-10-16T21:30:49+03:00 --- Checks if the given key exists in a dictionary. - Use the `in` operator to check if `d` contains `key`. ```py def key_in_dict(d, key): return (key in d) ``` ```py d = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4} key_in_dict(d, 'three') # True ``` ================================================ FILE: snippets/key-of-max.md ================================================ --- title: Key of max value type: snippet tags: [dictionary] cover: succulent-7 dateModified: 2021-01-07T23:15:48+02:00 --- Finds the key of the maximum value in a dictionary. - Use `max()` with the `key` parameter set to `dict.get()` to find and return the key of the maximum value in the given dictionary. ```py def key_of_max(d): return max(d, key = d.get) ``` ```py key_of_max({'a':4, 'b':0, 'c':13}) # c ``` ================================================ FILE: snippets/key-of-min.md ================================================ --- title: Key of min value type: snippet tags: [dictionary] cover: goat-wooden-cottage dateModified: 2021-01-07T23:15:48+02:00 --- Finds the key of the minimum value in a dictionary. - Use `min()` with the `key` parameter set to `dict.get()` to find and return the key of the minimum value in the given dictionary. ```py def key_of_min(d): return min(d, key = d.get) ``` ```py key_of_min({'a':4, 'b':0, 'c':13}) # b ``` ================================================ FILE: snippets/keys-only.md ================================================ --- title: Dictionary keys type: snippet tags: [dictionary,list] cover: succulent-5 dateModified: 2020-11-02T19:28:05+02:00 --- Creates a flat list of all the keys in a flat dictionary. - Use `dict.keys()` to return the keys in the given dictionary. - Return a `list()` of the previous result. ```py def keys_only(flat_dict): return list(flat_dict.keys()) ``` ```py ages = { 'Peter': 10, 'Isabel': 11, 'Anna': 9, } keys_only(ages) # ['Peter', 'Isabel', 'Anna'] ``` ================================================ FILE: snippets/km-to-miles.md ================================================ --- title: Km to miles type: snippet tags: [math] unlisted: true cover: interior-5 dateModified: 2021-01-04T12:47:04+02:00 --- Converts kilometers to miles. - Follows the conversion formula `mi = km * 0.621371`. ```py def km_to_miles(km): return km * 0.621371 ``` ```py km_to_miles(8.1) # 5.0331051 ``` ================================================ FILE: snippets/last.md ================================================ --- title: Last list element type: snippet tags: [list] cover: lake-runner dateModified: 2020-11-02T19:28:05+02:00 --- Returns the last element in a list. - Use `lst[-1]` to return the last element of the passed list. ```py def last(lst): return lst[-1] ``` ```py last([1, 2, 3]) # 3 ``` ================================================ FILE: snippets/lcm.md ================================================ --- title: Least common multiple type: snippet tags: [math,list] cover: fruit-feast dateModified: 2020-11-02T19:31:15+02:00 --- Returns the least common multiple of a list of numbers. - Use `functools.reduce()`, `math.gcd()` and `lcm(x, y) = x * y / gcd(x, y)` over the given list. ```py from functools import reduce from math import gcd def lcm(numbers): return reduce((lambda x, y: int(x * y / gcd(x, y))), numbers) ``` ```py lcm([12, 7]) # 84 lcm([1, 3, 4, 5]) # 60 ``` ================================================ FILE: snippets/longest-item.md ================================================ --- title: Longest item type: snippet tags: [list,string] cover: keyboard-tea dateModified: 2021-10-17T18:24:43+02:00 --- Takes any number of iterable objects or objects with a length property and returns the longest one. - Use `max()` with `len()` as the `key` to return the item with the greatest length. - If multiple items have the same length, the first one will be returned. ```py def longest_item(*args): return max(args, key = len) ``` ```py longest_item('this', 'is', 'a', 'testcase') # 'testcase' longest_item([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]) # [1, 2, 3, 4, 5] longest_item([1, 2, 3], 'foobar') # 'foobar' ``` ================================================ FILE: snippets/map-dictionary.md ================================================ --- title: Map list to dictionary type: snippet tags: [list,dictionary] excerpt: Maps the values of a list to a dictionary using a function. cover: colors-mural dateModified: 2020-11-02T19:28:27+02:00 --- Maps the values of a list to a dictionary using a function, where the key-value pairs consist of the original value as the key and the result of the function as the value. - Use `map()` to apply `fn` to each value of the list. - Use `zip()` to pair original values to the values produced by `fn`. - Use `dict()` to return an appropriate dictionary. ```py def map_dictionary(itr, fn): return dict(zip(itr, map(fn, itr))) ``` ```py map_dictionary([1, 2, 3], lambda x: x * x) # { 1: 1, 2: 4, 3: 9 } ``` ================================================ FILE: snippets/map-values.md ================================================ --- title: Map dictionary values type: snippet tags: [dictionary] cover: pineapple-laptop dateModified: 2020-11-02T19:28:27+02:00 --- Creates a dictionary with the same keys as the provided dictionary and values generated by running the provided function for each value. - Use `dict.items()` to iterate over the dictionary, assigning the values produced by `fn` to each key of a new dictionary. ```py def map_values(obj, fn): return dict((k, fn(v)) for k, v in obj.items()) ``` ```py users = { 'fred': { 'user': 'fred', 'age': 40 }, 'pebbles': { 'user': 'pebbles', 'age': 1 } } map_values(users, lambda u : u['age']) # {'fred': 40, 'pebbles': 1} ``` ================================================ FILE: snippets/max-by.md ================================================ --- title: Max list value based on function type: snippet tags: [math,list] cover: digital-nomad-3 dateModified: 2020-11-02T19:28:27+02:00 --- Returns the maximum value of a list, after mapping each element to a value using the provided function. - Use `map()` with `fn` to map each element to a value using the provided function. - Use `max()` to return the maximum value. ```py def max_by(lst, fn): return max(map(fn, lst)) ``` ```py max_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']) # 8 ``` ================================================ FILE: snippets/max-element-index.md ================================================ --- title: Index of max element type: snippet tags: [math,list] cover: dark-cloud dateModified: 2020-11-02T19:28:27+02:00 --- Returns the index of the element with the maximum value in a list. - Use `max()` and `list.index()` to get the maximum value in the list and return its index. ```py def max_element_index(arr): return arr.index(max(arr)) ``` ```py max_element_index([5, 8, 9, 7, 10, 3, 0]) # 4 ``` ================================================ FILE: snippets/max-n.md ================================================ --- title: N max elements type: snippet tags: [list,math] cover: red-succulent dateModified: 2020-11-02T19:28:27+02:00 --- Returns the `n` maximum elements from the provided list. - Use `sorted()` to sort the list. - Use slice notation to get the specified number of elements. - Omit the second argument, `n`, to get a one-element list. - If `n` is greater than or equal to the provided list's length, then return the original list (sorted in descending order). ```py def max_n(lst, n = 1): return sorted(lst, reverse = True)[:n] ``` ```py max_n([1, 2, 3]) # [3] max_n([1, 2, 3], 2) # [3, 2] ``` ================================================ FILE: snippets/median.md ================================================ --- title: Median type: snippet tags: [math] cover: little-bird dateModified: 2020-11-02T19:28:27+02:00 --- Finds the median of a list of numbers. - Sort the numbers of the list using `list.sort()`. - Find the median, which is either the middle element of the list if the list length is odd or the average of the two middle elements if the list length is even. - [`statistics.median()`](https://docs.python.org/3/library/statistics.html#statistics.median) provides similar functionality to this snippet. ```py def median(list): list.sort() list_length = len(list) if list_length % 2 == 0: return (list[int(list_length / 2) - 1] + list[int(list_length / 2)]) / 2 return float(list[int(list_length / 2)]) ``` ```py median([1, 2, 3]) # 2.0 median([1, 2, 3, 4]) # 2.5 ``` ================================================ FILE: snippets/merge-dictionaries.md ================================================ --- title: Merge dictionaries type: snippet tags: [dictionary] cover: plant-candle dateModified: 2020-11-02T19:28:27+02:00 --- Merges two or more dictionaries. - Create a new `dict` and loop over `dicts`, using `dictionary.update()` to add the key-value pairs from each one to the result. ```py def merge_dictionaries(*dicts): res = dict() for d in dicts: res.update(d) return res ``` ```py ages_one = { 'Peter': 10, 'Isabel': 11, } ages_two = { 'Anna': 9 } merge_dictionaries(ages_one, ages_two) # { 'Peter': 10, 'Isabel': 11, 'Anna': 9 } ``` ================================================ FILE: snippets/merge.md ================================================ --- title: Merge lists type: snippet tags: [list] cover: succulent-2 dateModified: 2020-11-02T19:28:27+02:00 --- Merges two or more lists into a list of lists, combining elements from each of the input lists based on their positions. - Use `max()` combined with a list comprehension to get the length of the longest list in the arguments. - Use `range()` in combination with the `max_length` variable to loop as many times as there are elements in the longest list. - If a list is shorter than `max_length`, use `fill_value` for the remaining items (defaults to `None`). - [`zip()`](https://docs.python.org/3/library/functions.html#zip) and [`itertools.zip_longest()`](https://docs.python.org/3/library/itertools.html#itertools.zip_longest) provide similar functionality to this snippet. ```py def merge(*args, fill_value = None): max_length = max([len(lst) for lst in args]) result = [] for i in range(max_length): result.append([ args[k][i] if i < len(args[k]) else fill_value for k in range(len(args)) ]) return result ``` ```py merge(['a', 'b'], [1, 2], [True, False]) # [['a', 1, True], ['b', 2, False]] merge(['a'], [1, 2], [True, False]) # [['a', 1, True], [None, 2, False]] merge(['a'], [1, 2], [True, False], fill_value = '_') # [['a', 1, True], ['_', 2, False]] ``` ================================================ FILE: snippets/miles-to-km.md ================================================ --- title: Miles to km type: snippet tags: [math] unlisted: true cover: interior-5 dateModified: 2021-01-04T12:47:04+02:00 --- Converts miles to kilometers. - Follows the conversion formula `km = mi * 1.609344`. ```py def miles_to_km(miles): return miles * 1.609344 ``` ```py miles_to_km(5.03) # 8.09500032 ``` ================================================ FILE: snippets/min-by.md ================================================ --- title: Min list value based on function type: snippet tags: [math,list] cover: purple-flower-field dateModified: 2020-11-02T19:28:27+02:00 --- Returns the minimum value of a list, after mapping each element to a value using the provided function. - Use `map()` with `fn` to map each element to a value using the provided function. - Use `min()` to return the minimum value. ```py def min_by(lst, fn): return min(map(fn, lst)) ``` ```py min_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']) # 2 ``` ================================================ FILE: snippets/min-element-index.md ================================================ --- title: Index of min element type: snippet tags: [math,list] cover: two-cities dateModified: 2020-11-02T19:28:27+02:00 --- Returns the index of the element with the minimum value in a list. - Use `min()` and `list.index()` to obtain the minimum value in the list and then return its index. ```py def min_element_index(arr): return arr.index(min(arr)) ``` ```py min_element_index([3, 5, 2, 6, 10, 7, 9]) # 2 ``` ================================================ FILE: snippets/min-n.md ================================================ --- title: N min elements type: snippet tags: [list,math] cover: balloons dateModified: 2020-11-02T19:28:27+02:00 --- Returns the `n` minimum elements from the provided list. - Use `sorted()` to sort the list. - Use slice notation to get the specified number of elements. - Omit the second argument, `n`, to get a one-element list. - If `n` is greater than or equal to the provided list's length, then return the original list (sorted in ascending order). ```py def min_n(lst, n = 1): return sorted(lst, reverse = False)[:n] ``` ```py min_n([1, 2, 3]) # [1] min_n([1, 2, 3], 2) # [1, 2] ``` ================================================ FILE: snippets/months-diff.md ================================================ --- title: Date difference in months type: snippet tags: [date] cover: succulent-11 dateModified: 2020-10-28T16:20:39+02:00 --- Calculates the month difference between two dates. - Subtract `start` from `end` and use `datetime.timedelta.days` to get the day difference. - Divide by `30` and use `math.ceil()` to get the difference in months (rounded up). ```py from math import ceil def months_diff(start, end): return ceil((end - start).days / 30) ``` ```py from datetime import date months_diff(date(2020, 10, 28), date(2020, 11, 25)) # 1 ``` ================================================ FILE: snippets/most-frequent.md ================================================ --- title: Most frequent element type: snippet tags: [list] cover: secret-tree dateModified: 2020-11-02T19:28:27+02:00 --- Returns the most frequent element in a list. - Use `set()` to get the unique values in `lst`. - Use `max()` to find the element that has the most appearances. ```py def most_frequent(lst): return max(set(lst), key = lst.count) ``` ```py most_frequent([1, 2, 1, 2, 3, 2, 1, 4, 2]) #2 ``` ================================================ FILE: snippets/n-times-string.md ================================================ --- title: Repeat string type: snippet tags: [string] cover: playing-fetch dateModified: 2020-11-02T19:28:27+02:00 --- Generates a string with the given string value repeated `n` number of times. - Repeat the string `n` times, using the `*` operator. ```py def n_times_string(s, n): return (s * n) ``` ```py n_times_string('py', 4) #'pypypypy' ``` ================================================ FILE: snippets/none.md ================================================ --- title: Test if every list element is falsy type: snippet tags: [list] cover: jars-on-shelf-2 dateModified: 2020-11-02T19:28:27+02:00 --- Checks if the provided function returns `True` for at least one element in the list. - Use `all()` and `fn` to check if `fn` returns `False` for all the elements in the list. ```py def none(lst, fn = lambda x: x): return all(not fn(x) for x in lst) ``` ```py none([0, 1, 2, 0], lambda x: x >= 2 ) # False none([0, 0, 0]) # True ``` ================================================ FILE: snippets/num-to-range.md ================================================ --- title: Map number to range type: snippet tags: [math] cover: round-leaves dateModified: 2021-04-05T18:25:46+03:00 --- Maps a number from one range to another range. - Return `num` mapped between `outMin`-`outMax` from `inMin`-`inMax`. ```py def num_to_range(num, inMin, inMax, outMin, outMax): return outMin + (float(num - inMin) / float(inMax - inMin) * (outMax - outMin)) ``` ```py num_to_range(5, 0, 10, 0, 100) # 50.0 ``` ================================================ FILE: snippets/offset.md ================================================ --- title: Offset list elements type: snippet tags: [list] cover: digital-nomad-10 dateModified: 2020-11-02T19:28:27+02:00 --- Moves the specified amount of elements to the end of the list. - Use slice notation to get the two slices of the list and combine them before returning. ```py def offset(lst, offset): return lst[offset:] + lst[:offset] ``` ```py offset([1, 2, 3, 4, 5], 2) # [3, 4, 5, 1, 2] offset([1, 2, 3, 4, 5], -2) # [4, 5, 1, 2, 3] ``` ================================================ FILE: snippets/pad-number.md ================================================ --- title: Pad number type: snippet tags: [string,math] cover: umbrellas dateModified: 2020-11-02T19:28:27+02:00 --- Pads a given number to the specified length. - Use `str.zfill()` to pad the number to the specified length, after converting it to a string. ```py def pad_number(n, l): return str(n).zfill(l) ``` ```py pad_number(1234, 6); # '001234' ``` ================================================ FILE: snippets/pad.md ================================================ --- title: Pad string type: snippet tags: [string] author: chalarangelo cover: digital-nomad-11 dateModified: 2020-10-04T01:53:05+03:00 --- Pads a string on both sides with the specified character, if it's shorter than the specified length. - Use `str.ljust()` and `str.rjust()` to pad both sides of the given string. - Omit the third argument, `char`, to use the whitespace character as the default padding character. ```py from math import floor def pad(s, length, char = ' '): return s.rjust(floor((len(s) + length)/2), char).ljust(length, char) ``` ```py pad('cat', 8) # ' cat ' pad('42', 6, '0') # '004200' pad('foobar', 3) # 'foobar' ``` ================================================ FILE: snippets/palindrome.md ================================================ --- title: Palindrome type: snippet tags: [string] cover: succulent-6 dateModified: 2020-11-02T19:28:27+02:00 --- Checks if the given string is a palindrome. - Use `str.lower()` and `re.sub()` to convert to lowercase and remove non-alphanumeric characters from the given string. - Then, compare the new string with its reverse, using slice notation. ```py from re import sub def palindrome(s): s = sub('[\W_]', '', s.lower()) return s == s[::-1] ``` ```py palindrome('taco cat') # True ``` ================================================ FILE: snippets/pluck.md ================================================ --- title: Pluck values from list of dictionaries type: snippet tags: [list,dictionary] cover: succulent-9 dateModified: 2020-10-22T10:09:44+03:00 --- Converts a list of dictionaries into a list of values corresponding to the specified `key`. - Use a list comprehension and `dict.get()` to get the value of `key` for each dictionary in `lst`. ```py def pluck(lst, key): return [x.get(key) for x in lst] ``` ```py simpsons = [ { 'name': 'lisa', 'age': 8 }, { 'name': 'homer', 'age': 36 }, { 'name': 'marge', 'age': 34 }, { 'name': 'bart', 'age': 10 } ] pluck(simpsons, 'age') # [8, 36, 34, 10] ``` ================================================ FILE: snippets/powerset.md ================================================ --- title: Powerset type: snippet tags: [math,list] author: chalarangelo cover: rock-climbing dateModified: 2020-11-02T19:28:27+02:00 --- Returns the powerset of a given iterable. - Use `list()` to convert the given value to a list. - Use `range()` and `itertools.combinations()` to create a generator that returns all subsets. - Use `itertools.chain.from_iterable()` and `list()` to consume the generator and return a list. ```py from itertools import chain, combinations def powerset(iterable): s = list(iterable) return list(chain.from_iterable(combinations(s, r) for r in range(len(s)+1))) ``` ```py powerset([1, 2]) # [(), (1,), (2,), (1, 2)] ``` ================================================ FILE: snippets/rads-to-degrees.md ================================================ --- title: Radians to degrees type: snippet tags: [math] cover: watermelon-bike dateModified: 2020-11-02T19:28:27+02:00 --- Converts an angle from radians to degrees. - Use `math.pi` and the radian to degree formula to convert the angle from radians to degrees. ```py from math import pi def rads_to_degrees(rad): return (rad * 180.0) / pi ``` ```py from math import pi rads_to_degrees(pi / 2) # 90.0 ``` ================================================ FILE: snippets/reverse-number.md ================================================ --- title: Reverse number type: snippet tags: [math] cover: taking-photos dateModified: 2020-11-02T19:28:27+02:00 --- Reverses a number. - Use `str()` to convert the number to a string, slice notation to reverse it and `str.replace()` to remove the sign. - Use `float()` to convert the result to a number and `math.copysign()` to copy the original sign. ```py from math import copysign def reverse_number(n): return copysign(float(str(n)[::-1].replace('-', '')), n) ``` ```py reverse_number(981) # 189 reverse_number(-500) # -5 reverse_number(73.6) # 6.37 reverse_number(-5.23) # -32.5 ``` ================================================ FILE: snippets/reverse.md ================================================ --- title: Reverse list type: snippet tags: [list,string] cover: industrial-tokyo dateModified: 2020-11-02T19:28:27+02:00 --- Reverses a list or a string. - Use slice notation to reverse the list or string. ```py def reverse(itr): return itr[::-1] ``` ```py reverse([1, 2, 3]) # [3, 2, 1] reverse('snippet') # 'teppins' ``` ================================================ FILE: snippets/rgb-to-hex.md ================================================ --- title: RGB to hex type: snippet tags: [string,math] cover: campfire dateModified: 2020-11-02T19:28:27+02:00 --- Converts the values of RGB components to a hexadecimal color code. - Create a placeholder for a zero-padded hexadecimal value using `'{:02X}'` and copy it three times. - Use `str.format()` on the resulting string to replace the placeholders with the given values. ```py def rgb_to_hex(r, g, b): return ('{:02X}' * 3).format(r, g, b) ``` ```py rgb_to_hex(255, 165, 1) # 'FFA501' ``` ================================================ FILE: snippets/roll.md ================================================ --- title: Rotate list elements type: snippet tags: [list] cover: colorful-pots dateModified: 2020-11-02T19:15:44+02:00 --- Moves the specified amount of elements to the start of the list. - Use slice notation to get the two slices of the list and combine them before returning. ```py def roll(lst, offset): return lst[-offset:] + lst[:-offset] ``` ```py roll([1, 2, 3, 4, 5], 2) # [4, 5, 1, 2, 3] roll([1, 2, 3, 4, 5], -2) # [3, 4, 5, 1, 2] ``` ================================================ FILE: snippets/sample.md ================================================ --- title: Random element in list type: snippet tags: [list,random] cover: walking-on-top dateModified: 2020-10-28T11:45:34+02:00 --- Returns a random element from a list. - Use `random.choice()` to get a random element from `lst`. ```py from random import choice def sample(lst): return choice(lst) ``` ```py sample([3, 7, 9, 11]) # 9 ``` ================================================ FILE: snippets/shuffle.md ================================================ --- title: Shuffle list type: snippet tags: [list,random] cover: tent-stars dateModified: 2020-11-02T19:28:35+02:00 --- Randomizes the order of the values of an list, returning a new list. - Uses the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) to reorder the elements of the list. - [`random.shuffle`](https://docs.python.org/3/library/random.html#random.shuffle) provides similar functionality to this snippet. ```py from copy import deepcopy from random import randint def shuffle(lst): temp_lst = deepcopy(lst) m = len(temp_lst) while (m): m -= 1 i = randint(0, m) temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m] return temp_lst ``` ```py foo = [1, 2, 3] shuffle(foo) # [2, 3, 1], foo = [1, 2, 3] ``` ================================================ FILE: snippets/similarity.md ================================================ --- title: List similarity type: snippet tags: [list] cover: sunflowers dateModified: 2020-11-02T19:28:35+02:00 --- Returns a list of elements that exist in both lists. - Use a list comprehension on `a` to only keep values contained in both lists. ```py def similarity(a, b): return [item for item in a if item in b] ``` ```py similarity([1, 2, 3], [1, 2, 4]) # [1, 2] ``` ================================================ FILE: snippets/slugify.md ================================================ --- title: String to slug type: snippet tags: [string,regexp] cover: sliced-fruits dateModified: 2020-10-25T12:43:20+02:00 --- Converts a string to a URL-friendly slug. - Use `str.lower()` and `str.strip()` to normalize the input string. - Use `re.sub()` to to replace spaces, dashes and underscores with `-` and remove special characters. ```py import re def slugify(s): s = s.lower().strip() s = re.sub(r'[^\w\s-]', '', s) s = re.sub(r'[\s_-]+', '-', s) s = re.sub(r'^-+|-+$', '', s) return s ``` ```py slugify('Hello World!') # 'hello-world' ``` ================================================ FILE: snippets/snake.md ================================================ --- title: Snakecase string type: snippet tags: [string,regexp] cover: organizer dateModified: 2020-11-02T19:28:35+02:00 --- Converts a string to snake case. - Use `re.sub()` to match all words in the string, `str.lower()` to lowercase them. - Use `re.sub()` to replace any `-` characters with spaces. - Finally, use `str.join()` to combine all words using `-` as the separator. ```py from re import sub def snake(s): return '_'.join( sub('([A-Z][a-z]+)', r' \1', sub('([A-Z]+)', r' \1', s.replace('-', ' '))).split()).lower() ``` ```py snake('camelCase') # 'camel_case' snake('some text') # 'some_text' snake('some-mixed_string With spaces_underscores-and-hyphens') # 'some_mixed_string_with_spaces_underscores_and_hyphens' snake('AllThe-small Things') # 'all_the_small_things' ``` ================================================ FILE: snippets/some.md ================================================ --- title: Test if some list elements are truthy type: snippet tags: [list] cover: pink-flower-tree dateModified: 2020-11-02T19:28:35+02:00 --- Checks if the provided function returns `True` for at least one element in the list. - Use `any()` in combination with `map()` to check if `fn` returns `True` for any element in the list. ```py def some(lst, fn = lambda x: x): return any(map(fn, lst)) ``` ```py some([0, 1, 2, 0], lambda x: x >= 2 ) # True some([0, 0, 1, 0]) # True ``` ================================================ FILE: snippets/sort-by-indexes.md ================================================ --- title: Sort list by indexes type: snippet tags: [list] cover: little-white-flowers dateModified: 2020-11-02T19:28:35+02:00 --- Sorts one list based on another list containing the desired indexes. - Use `zip()` and `sorted()` to combine and sort the two lists, based on the values of `indexes`. - Use a list comprehension to get the first element of each pair from the result. - Use the `reverse` parameter in `sorted()` to sort the dictionary in reverse order, based on the third argument. ```py def sort_by_indexes(lst, indexes, reverse=False): return [val for (_, val) in sorted(zip(indexes, lst), key=lambda x: \ x[0], reverse=reverse)] ``` ```py a = ['eggs', 'bread', 'oranges', 'jam', 'apples', 'milk'] b = [3, 2, 6, 4, 1, 5] sort_by_indexes(a, b) # ['apples', 'bread', 'eggs', 'jam', 'milk', 'oranges'] sort_by_indexes(a, b, True) # ['oranges', 'milk', 'jam', 'eggs', 'bread', 'apples'] ``` ================================================ FILE: snippets/sort-dict-by-key.md ================================================ --- title: Sort dictionary by key type: snippet tags: [dictionary] cover: laptop-plants dateModified: 2020-11-02T19:28:35+02:00 --- Sorts the given dictionary by key. - Use `dict.items()` to get a list of tuple pairs from `d` and sort it using `sorted()`. - Use `dict()` to convert the sorted list back to a dictionary. - Use the `reverse` parameter in `sorted()` to sort the dictionary in reverse order, based on the second argument. ```py def sort_dict_by_key(d, reverse = False): return dict(sorted(d.items(), reverse = reverse)) ``` ```py d = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4} sort_dict_by_key(d) # {'five': 5, 'four': 4, 'one': 1, 'three': 3, 'two': 2} sort_dict_by_key(d, True) # {'two': 2, 'three': 3, 'one': 1, 'four': 4, 'five': 5} ``` ================================================ FILE: snippets/sort-dict-by-value.md ================================================ --- title: Sort dictionary by value type: snippet tags: [dictionary] cover: jars-on-shelf dateModified: 2021-01-08T00:56:50+02:00 --- Sorts the given dictionary by value. - Use `dict.items()` to get a list of tuple pairs from `d` and sort it using a lambda function and `sorted()`. - Use `dict()` to convert the sorted list back to a dictionary. - Use the `reverse` parameter in `sorted()` to sort the dictionary in reverse order, based on the second argument. - **⚠️ NOTICE:** Dictionary values must be of the same type. ```py def sort_dict_by_value(d, reverse = False): return dict(sorted(d.items(), key = lambda x: x[1], reverse = reverse)) ``` ```py d = {'one': 1, 'three': 3, 'five': 5, 'two': 2, 'four': 4} sort_dict_by_value(d) # {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5} sort_dict_by_value(d, True) # {'five': 5, 'four': 4, 'three': 3, 'two': 2, 'one': 1} ``` ================================================ FILE: snippets/split-lines.md ================================================ --- title: Split into lines type: snippet tags: [string] cover: succulent-4 dateModified: 2020-11-02T19:28:35+02:00 --- Splits a multiline string into a list of lines. - Use `str.split()` and `'\n'` to match line breaks and create a list. - [`str.splitlines()`](https://docs.python.org/3/library/stdtypes.html#str.splitlines) provides similar functionality to this snippet. ```py def split_lines(s): return s.split('\n') ``` ```py split_lines('This\nis a\nmultiline\nstring.\n') # ['This', 'is a', 'multiline', 'string.' , ''] ``` ================================================ FILE: snippets/spread.md ================================================ --- title: Spread list type: snippet tags: [list] cover: digital-nomad-14 dateModified: 2020-09-15T16:13:06+03:00 --- Flattens a list, by spreading its elements into a new list. - Loop over elements, use `list.extend()` if the element is a list, `list.append()` otherwise. ```py def spread(arg): ret = [] for i in arg: ret.extend(i) if isinstance(i, list) else ret.append(i) return ret ``` ```py spread([1, 2, 3, [4, 5, 6], [7], 8, 9]) # [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` ================================================ FILE: snippets/sum-by.md ================================================ --- title: Sum list based on function type: snippet tags: [math,list] cover: horse-sunset dateModified: 2020-11-02T19:28:35+02:00 --- Calculates the sum of a list, after mapping each element to a value using the provided function. - Use `map()` with `fn` to map each element to a value using the provided function. - Use `sum()` to return the sum of the values. ```py def sum_by(lst, fn): return sum(map(fn, lst)) ``` ```py sum_by([{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }], lambda v : v['n']) # 20 ``` ================================================ FILE: snippets/sum-of-powers.md ================================================ --- title: Sum of powers type: snippet tags: [math] cover: river-flow dateModified: 2020-11-02T19:28:35+02:00 --- Returns the sum of the powers of all the numbers from `start` to `end` (both inclusive). - Use `range()` in combination with a list comprehension to create a list of elements in the desired range raised to the given `power`. - Use `sum()` to add the values together. - Omit the second argument, `power`, to use a default power of `2`. - Omit the third argument, `start`, to use a default starting value of `1`. ```py def sum_of_powers(end, power = 2, start = 1): return sum([(i) ** power for i in range(start, end + 1)]) ``` ```py sum_of_powers(10) # 385 sum_of_powers(10, 3) # 3025 sum_of_powers(10, 3, 5) # 2925 ``` ================================================ FILE: snippets/symmetric-difference-by.md ================================================ --- title: List symmetric difference based on function type: snippet tags: [list] cover: succulent-1 dateModified: 2020-11-02T19:28:35+02:00 --- Returns the symmetric difference between two lists, after applying the provided function to each list element of both. - Create a `set` by applying `fn` to each element in every list. - Use a list comprehension in combination with `fn` on each of them to only keep values not contained in the previously created set of the other. ```py def symmetric_difference_by(a, b, fn): (_a, _b) = (set(map(fn, a)), set(map(fn, b))) return [item for item in a if fn(item) not in _b] + [item for item in b if fn(item) not in _a] ``` ```py from math import floor symmetric_difference_by([2.1, 1.2], [2.3, 3.4], floor) # [1.2, 3.4] ``` ================================================ FILE: snippets/symmetric-difference.md ================================================ --- title: List symmetric difference type: snippet tags: [list] cover: ice dateModified: 2020-11-02T19:28:35+02:00 --- Returns the symmetric difference between two iterables, without filtering out duplicate values. - Create a `set` from each list. - Use a list comprehension on each of them to only keep values not contained in the previously created set of the other. ```py def symmetric_difference(a, b): (_a, _b) = (set(a), set(b)) return [item for item in a if item not in _b] + [item for item in b if item not in _a] ``` ```py symmetric_difference([1, 2, 3], [1, 2, 4]) # [3, 4] ``` ================================================ FILE: snippets/tail.md ================================================ --- title: List tail type: snippet tags: [list] cover: meteora dateModified: 2020-11-02T19:28:35+02:00 --- Returns all elements in a list except for the first one. - Use slice notation to return the last element if the list's length is more than `1`. - Otherwise, return the whole list. ```py def tail(lst): return lst[1:] if len(lst) > 1 else lst ``` ```py tail([1, 2, 3]) # [2, 3] tail([1]) # [1] ``` ================================================ FILE: snippets/take-right.md ================================================ --- title: Remove list elements from the end type: snippet tags: [list] author: chalarangelo cover: three-vases dateModified: 2020-09-15T16:13:06+03:00 --- Returns a list with `n` elements removed from the end. - Use slice notation to create a slice of the list with `n` elements taken from the end. ```py def take_right(itr, n = 1): return itr[-n:] ``` ```py take_right([1, 2, 3], 2) # [2, 3] take_right([1, 2, 3]) # [3] ``` ================================================ FILE: snippets/take.md ================================================ --- title: Remove list elements type: snippet tags: [list] author: chalarangelo cover: sea-view-2 dateModified: 2020-09-15T16:13:06+03:00 --- Returns a list with `n` elements removed from the beginning. - Use slice notation to create a slice of the list with `n` elements taken from the beginning. ```py def take(itr, n = 1): return itr[:n] ``` ```py take([1, 2, 3], 5) # [1, 2, 3] take([1, 2, 3], 0) # [] ``` ================================================ FILE: snippets/to-binary.md ================================================ --- title: Number to binary type: snippet tags: [math] cover: digital-nomad-13 dateModified: 2020-10-07T19:46:01+03:00 --- Returns the binary representation of the given number. - Use `bin()` to convert a given decimal number into its binary equivalent. ```py def to_binary(n): return bin(n) ``` ```py to_binary(100) # 0b1100100 ``` ================================================ FILE: snippets/to-dictionary.md ================================================ --- title: Lists to dictionary type: snippet tags: [list,dictionary] excerpt: Combines two lists into a dictionary, using the first one as the keys and the second one as the values. cover: purple-sunset dateModified: 2020-11-02T19:28:35+02:00 --- Combines two lists into a dictionary, where the elements of the first one serve as the keys and the elements of the second one serve as the values. The values of the first list need to be unique and hashable. - Use `zip()` in combination with `dict()` to combine the values of the two lists into a dictionary. ```py def to_dictionary(keys, values): return dict(zip(keys, values)) ``` ```py to_dictionary(['a', 'b'], [1, 2]) # { a: 1, b: 2 } ``` ================================================ FILE: snippets/to-hex.md ================================================ --- title: Number to hex type: snippet tags: [math] cover: green-plant dateModified: 2020-10-09T09:45:47+03:00 --- Returns the hexadecimal representation of the given number. - Use `hex()` to convert a given decimal number into its hexadecimal equivalent. ```py def to_hex(dec): return hex(dec) ``` ```py to_hex(41) # 0x29 to_hex(332) # 0x14c ``` ================================================ FILE: snippets/to-iso-date.md ================================================ --- title: Date to ISO format type: snippet tags: [date] cover: succulent-red-light dateModified: 2021-01-07T23:30:28+02:00 --- Converts a date to its ISO-8601 representation. - Use `datetime.datetime.isoformat()` to convert the given `datetime.datetime` object to an ISO-8601 date. ```py from datetime import datetime def to_iso_date(d): return d.isoformat() ``` ```py from datetime import datetime to_iso_date(datetime(2020, 10, 25)) # 2020-10-25T00:00:00 ``` ================================================ FILE: snippets/to-roman-numeral.md ================================================ --- title: Integer to roman numeral type: snippet tags: [math,string] cover: tram-car dateModified: 2020-11-02T19:28:35+02:00 --- Converts an integer to its roman numeral representation. Accepts value between `1` and `3999` (both inclusive). - Create a lookup list containing tuples in the form of (roman value, integer). - Use a `for` loop to iterate over the values in `lookup`. - Use `divmod()` to update `num` with the remainder, adding the roman numeral representation to the result. ```py def to_roman_numeral(num): lookup = [ (1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'), (100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I'), ] res = '' for (n, roman) in lookup: (d, num) = divmod(num, n) res += roman * d return res ``` ```py to_roman_numeral(3) # 'III' to_roman_numeral(11) # 'XI' to_roman_numeral(1998) # 'MCMXCVIII' ``` ================================================ FILE: snippets/transpose.md ================================================ --- title: Transpose matrix type: snippet tags: [list] cover: lake-bench dateModified: 2020-11-02T19:28:35+02:00 --- Transposes a two-dimensional list. - Use `*lst` to get the provided list as tuples. - Use `zip()` in combination with `list()` to create the transpose of the given two-dimensional list. ```py def transpose(lst): return list(zip(*lst)) ``` ```py transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]) # [(1, 4, 7, 10), (2, 5, 8, 11), (3, 6, 9, 12)] ``` ================================================ FILE: snippets/unfold.md ================================================ --- title: Unfold list type: snippet tags: [function,list] cover: painters-desk dateModified: 2020-11-02T19:28:35+02:00 --- Builds a list, using an iterator function and an initial seed value. - The iterator function accepts one argument (`seed`) and must always return a list with two elements ([`value`, `nextSeed`]) or `False` to terminate. - Use a generator function, `fn_generator`, that uses a `while` loop to call the iterator function and `yield` the `value` until it returns `False`. - Use a list comprehension to return the list that is produced by the generator, using the iterator function. ```py def unfold(fn, seed): def fn_generator(val): while True: val = fn(val[1]) if val == False: break yield val[0] return [i for i in fn_generator([None, seed])] ``` ```py f = lambda n: False if n > 50 else [-n, n + 10] unfold(f, 10) # [-10, -20, -30, -40, -50] ``` ================================================ FILE: snippets/union-by.md ================================================ --- title: List union based on function type: snippet tags: [list] cover: sunrise-over-city dateModified: 2020-11-02T19:28:35+02:00 --- Returns every element that exists in any of the two lists once, after applying the provided function to each element of both. - Create a `set` by applying `fn` to each element in `a`. - Use a list comprehension in combination with `fn` on `b` to only keep values not contained in the previously created set, `_a`. - Finally, create a `set` from the previous result and `a` and transform it into a `list` ```py def union_by(a, b, fn): _a = set(map(fn, a)) return list(set(a + [item for item in b if fn(item) not in _a])) ``` ```py from math import floor union_by([2.1], [1.2, 2.3], floor) # [2.1, 1.2] ``` ================================================ FILE: snippets/union.md ================================================ --- title: List union type: snippet tags: [list] cover: river-houses dateModified: 2020-11-02T19:28:35+02:00 --- Returns every element that exists in any of the two lists once. - Create a `set` with all values of `a` and `b` and convert to a `list`. ```py def union(a, b): return list(set(a + b)) ``` ```py union([1, 2, 3], [4, 3, 2]) # [1, 2, 3, 4] ``` ================================================ FILE: snippets/unique-elements.md ================================================ --- title: Unique elements in list type: snippet tags: [list] cover: cold-mountains dateModified: 2020-09-15T16:13:06+03:00 --- Returns the unique elements in a given list. - Create a `set` from the list to discard duplicated values, then return a `list` from it. ```py def unique_elements(li): return list(set(li)) ``` ```py unique_elements([1, 2, 2, 3, 4, 3]) # [1, 2, 3, 4] ``` ================================================ FILE: snippets/values-only.md ================================================ --- title: Dictionary values type: snippet tags: [dictionary,list] cover: colorful-lounge dateModified: 2020-11-02T19:28:35+02:00 --- Returns a flat list of all the values in a flat dictionary. - Use `dict.values()` to return the values in the given dictionary. - Return a `list()` of the previous result. ```py def values_only(flat_dict): return list(flat_dict.values()) ``` ```py ages = { 'Peter': 10, 'Isabel': 11, 'Anna': 9, } values_only(ages) # [10, 11, 9] ``` ================================================ FILE: snippets/weighted-average.md ================================================ --- title: Weighted average type: snippet tags: [math,list] cover: digital-nomad-4 dateModified: 2020-12-24T15:00:53+02:00 --- Returns the weighted average of two or more numbers. - Use `sum()` to sum the products of the numbers by their weight and to sum the weights. - Use `zip()` and a list comprehension to iterate over the pairs of values and weights. ```py def weighted_average(nums, weights): return sum(x * y for x, y in zip(nums, weights)) / sum(weights) ``` ```py weighted_average([1, 2, 3], [0.6, 0.2, 0.3]) # 1.72727 ``` ================================================ FILE: snippets/when.md ================================================ --- title: Apply function when true type: snippet tags: [function] cover: interior-10 dateModified: 2020-11-09T23:56:11+02:00 --- Tests a value, `x`, against a testing function, conditionally applying a function. - Check if the value of `predicate()` is `True` for `x` and if so call `when_true()`, otherwise return `x`. ```py def when(predicate, when_true): return lambda x: when_true(x) if predicate(x) else x ``` ```py double_even_numbers = when(lambda x: x % 2 == 0, lambda x : x * 2) double_even_numbers(2) # 4 double_even_numbers(1) # 1 ``` ================================================ FILE: snippets/words.md ================================================ --- title: String to words type: snippet tags: [string,regexp] cover: rocky-lake dateModified: 2020-11-02T19:28:35+02:00 --- Converts a given string into a list of words. - Use `re.findall()` with the supplied `pattern` to find all matching substrings. - Omit the second argument to use the default regexp, which matches alphanumeric and hyphens. ```py import re def words(s, pattern = '[a-zA-Z-]+'): return re.findall(pattern, s) ``` ```py words('I love Python!!') # ['I', 'love', 'Python'] words('python, javaScript & coffee') # ['python', 'javaScript', 'coffee'] words('build -q --out one-item', r'\b[a-zA-Z-]+\b') # ['build', 'q', 'out', 'one-item'] ```