Ta-da! You’re left with a list of what you want (spongecase-d letters) given what you have (index and letter) from the original string. List Comprehensions are used when a list should be populated consistently according to a known pattern, often to extract data from an existing collection.įor example, let’s say you have some JSON data from an API, which, when parsed by a library of requests, winds up being a list of thousands of phone numbers with each stored as a dictionary with several fields: What exactly are List Comprehensions, and why would we need them when lists are so flexible out-of-the-box? Like Lambda functions, you can easily pass ListComps dynamically.You can see the input and the way it’s modified.You automatically know the intended output.With practice, you’ll prefer to read code that is written with comprehensions because: Because comprehensions usually (but not necessarily) take place on a single line, the brain can digest more meaning at once. There’s much less room for error in a ListComp than a nested for loop. The answer is practice, and room for error. The reason I consider the performance advantage not to be a major factor is because if performance is a major concern, you might want to look at a different datatype altogether – such as Dictionary.įor List Comprehensions or Dictionary Comprehensions beginners, it can be hard to see how they could be easier to read than the good ol’ list declaration and manipulation using explicit methods. ( Note: You may see List Comprehensions variously referred to as comprehensions, List Comprehensions, or ListComps.) ListComps have a moderate performance advantage. Code with List Comprehensions is even easier to read (with a bit of practice).Nothing could be easier to read, and if your lists aren’t broken, why fix them? There are actually two major reasons, and even a bonus one:
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |