<jupyter_start><jupyter_text>LoopsLoops are a way to repeatedly execute some code. Here's an example:<jupyter_code>planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
for planet in planets:
    print(planet, end=' ') # print all on same line<jupyter_output>Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune<jupyter_text>The **``for``** loop specifies:- The variable name to use (in this case, `planet`)- The set of values to loop over (in this case, `planets`)You use the word **``in``** to link them together.The object to the right of the "``in``" can be any object that supports iteration. Basically, if it can be thought of as a group of things, you can probably loop over it. In addition to lists, we can iterate over the elements of a tuple:<jupyter_code>multiplicands = (2, 2, 2, 3, 3, 5)
product = 1
for mult in multiplicands:
    product = product * mult
product<jupyter_output><empty_output><jupyter_text>You can even loop through each character in a string:<jupyter_code>s = 'steganograpHy is the practicE of conceaLing a file, message, image, or video within another fiLe, message, image, Or video.'
msg = ''
# print all the uppercase letters in s, one at a time
for char in s:
    if char.isupper():
        print(char, end='')<jupyter_output>HELLO<jupyter_text>range()**`range()`** is a function that returns a sequence of numbers. It turns out to be very useful for writing loops.For example, if we want to repeat some action 5 times:<jupyter_code>for i in range(5):
    print("Doing important work. i =", i)<jupyter_output><empty_output><jupyter_text>``while`` loopsThe other type of loop in Python is a ``while`` loop, which iterates until some condition is met:<jupyter_code>i = 0
while i < 10:
    print(i, end=' ')
    i += 1<jupyter_output>0 1 2 3 4 5 6 7 8 9<jupyter_text>The argument of the ``while`` loop is evaluated as a boolean statement, and the loop is executed until the statement evaluates to False.  List ComprehensionsList comprehensions are one of Python's most beloved and unique features. *But it may be difficult to start with*, so be patient.- It provides a concise way to create lists.- It consists of squarre brackets containing an expression followed by a `for` clause, then zero or more `for` or `if` clauses. The expressions can be anything, meaning you can put in all kinds of objects in lists.- The result will be a new list resulting from evaluating the expression in the context of the `for` and `if` clauses which follow it.  SyntaxThe list comprehension starts with a `[` and `]`, to help you remember that the result is going to be a list.The basic syntax is:```python[ expression for item in list if conditional ]```This is equivalent to:```pythonfor item in list:    if conditional:        expression``` Interpretation```pythonnew_list = [expression(i) for i in old_list if filter(i)]```- **new_list**: The new list (result).- **expression(i)**: Expression is based on the variable used for each element in the old list.- **for i in old_list**: The word for followed by the variable name to use, followed by the word in theold list.- **if filter(i)**: Apply a filter with an If-statement.The easiest way to understand them is probably to just look at a few examples:<jupyter_code>squares = [n**2 for n in range(10)]
squares<jupyter_output><empty_output><jupyter_text>Here's how we would do the same thing without a list comprehension:<jupyter_code>squares = []
for n in range(10):
    squares.append(n**2)
squares<jupyter_output><empty_output><jupyter_text>Now, adding an `if` condition:<jupyter_code>short_planets = [planet for planet in planets if len(planet) < 6]
short_planets<jupyter_output><empty_output><jupyter_text>(If you're familiar with SQL, you might think of this as being like a "WHERE" clause)Here's an example of filtering with an `if` condition *and* applying some transformation to the loop variable:<jupyter_code># str.upper() returns an all-caps version of a string
loud_short_planets = [planet.upper() + '!' for planet in planets if len(planet) < 6]
loud_short_planets<jupyter_output><empty_output><jupyter_text>People usually write these on a single line, but you might find the structure clearer when it's split up over 3 lines:<jupyter_code>[
    planet.upper() + '!' 
    for planet in planets 
    if len(planet) < 6
]<jupyter_output><empty_output><jupyter_text>(Continuing the SQL analogy, you could think of these three lines as SELECT, FROM, and WHERE)The expression on the left doesn't technically have to involve the loop variable (though it'd be pretty unusual for it not to). What do you think the expression below will evaluate to?<jupyter_code>[32 for planet in planets]<jupyter_output><empty_output><jupyter_text>List comprehensions combined with functions like `min`, `max`, and `sum` can lead to impressive one-line solutions for problems that would otherwise require several lines of code. For example, compare the following two cells of code that do the same thing.<jupyter_code>def count_negatives(nums):
    """Return the number of negative numbers in the given list.
    
    >>> count_negatives([5, -1, -2, 0, 3])
    2
    """
    n_negative = 0
    for num in nums:
        if num < 0:
            n_negative = n_negative + 1
    return n_negative<jupyter_output><empty_output><jupyter_text>Here's a solution using a list comprehension:<jupyter_code>def count_negatives(nums):
    return len([num for num in nums if num < 0])<jupyter_output><empty_output><jupyter_text>*Much better, right?*Well if all we care about is minimizing the length of our code, this third solution is better still!<jupyter_code>def count_negatives(nums):
    # Reminder: in the "booleans and conditionals" exercises, we learned about a quirk of 
    # Python where it calculates something like True + True + False + True to be equal to 3.
    return sum([num < 0 for num in nums])<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.09126180836707153, 'fraction_numerical': 0.007928475033738192, 'mean_word_length': 4.917165668662674, 'pattern_counts': {'":': 0, '<': 61, '<?xml version=': 0, '>': 57, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '14', 'dir': 'jupyter-structured-clean-dedup', 'id': '56580', 'license': 'MIT', 'n_tokens_mistral': 1831, 'n_tokens_neox': 1738, 'n_words': 782, 'path': 'python-for-data/Lec05 - Loops and List Comprehensions.ipynb', 'repo_name': 'phamdinhtuan200382/atom-assignments', 'size': '5928'}