reading notes for code fellows
List comprehension is an incredibly useful asset in allowing you to make your code clearer and more concise, as well as more manageable than a complicated loop or extra variables often are.
There are three pieces of python list comprehension. An average expression is written as new_list = [expression for item in list]. Expression refers to the expression we’d like to carry out, item is the object the expression will work on, and list is the iterable list of objects to build our new list from. In short, you are assigning to a new list, each item in an old list with something new done to it. One major use of this is for creating a list with a range, ex nums = [x for x in range(10)] gives us [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. If you want to use it as a filter, you can also do that by adding an if statement to the end, such as even = [x for x in range(10) if x % 2 == 0] will only return even numbers. This also gives you the ability to use things like built in methods, such as in lower_case = [letter.lower() for letter in ['A', 'B', 'C']].
Files can also be utilized with list comprehension, as well as python functions written by the user rather than being embeded.
It would be a bit strange to say that using list comprehension is like refactoring your code, since that is exactly what it is doing, but in a way it is almost an analogy for itself - taking a large amount of unnecessary code and making it more manageable in the scale of itself and the whole of the project.