1 Square List
If you want to create a list containing squares from 1 to 10, you can do so:
squares = [] for x in range(10): (x**2)
This is a simple example, but it can be created more succinctly using list generators.
squares = [x**2 for x in range(10)]
The simplest list generator starts with square brackets, inside which is an expression followed by a for statement. The list generator always returns a list.
2 List of numbers divisible by 3
Usually, you might write it like this:
numbers = [] for x in range(100): if x % 3 == 0: (x)
You can conditionally add items to a list by including an if statement in the list constructor. To create a list of numbers between 0 and 100 that are divisible by 3, you can use list derivatives:
numbers = [x for x in range(100) if x % 3 == 0]
3 Finding prime numbers
This is usually accomplished using several lines of code.
noprimes = [] for i in range(2, 8): for j in range(i*2, 50, i): (j) primes = [] for x in range(2, 50): if x not in noprimes: (x)
However, you can use two list generators to simplify the code.
noprimes = [j for i in range(2, 8) for j in range(i*2, 50, i)] primes = [x for x in range(2, 50) if x not in noprimes]
The first line of code uses multiple layers of for loops in a list generator. The first loop is an outer loop and the second is an inner loop. To find the primes, we first find a list of nonprimes. This list of nonprime numbers is generated by finding multiples of 2-7. Then we loop through the numbers and see if each number is in the list of non-primes.
Fix: As pointed out by soyer on reddit, it's more efficient to use sets to look up noprimes (the attribute parameters in the code, paraphrasing). Since noprimes are supposed to contain only unique values, and since we frequently have to check if a value exists, we should use sets. The syntax for using collections is similar to the syntax for using lists, so we can use them like this:
noprimes = set(j for i in range(2, 8) for j in range(i*2, 50, i)) primes = [x for x in range(2, 50) if x not in noprimes]
4 Nested list dimensionality reduction
Suppose you have a list of lists (lists containing lists) or a matrix that
matrix = [[0,1,2,3], [4,5,6,7], [8,9,10,11]]
And you want to downscale it to a one-dimensional list. You can do that:
flattened = [] for row in matrix: for i in row: (i)
Use list generators:
flattened = [i for row in matrix for i in row]
This uses two for loops to iterate through the entire matrix. The outer (first) loop iterates by row, and the inner (second) loop iterates over each item in that row.
5 Simulate multiple coin toss events
Assuming that you need to simulate multiple coin toss events, where 0 means heads and 1 means tails, you can write the code like this:
from random import random results = [] for x in range(10): (int(round(random())))
Or use list generators to make the code more concise:
from random import random results = [int(round(random())) for x in range(10)]
Here the range function has been used to loop 10 times. Each time we rounded the output of random(). Since the random() function returns a floating-point number from 0 to 1, rounding the output returns 0 or 1. The round() function returns a floating-point number, which is converted to an integer using int() and added to the list.
6 Removing vowel letters from sentences
Suppose you have a sentence that
sentence = 'Your mother was a hamster'
and you want to remove all the vowel letters. We can easily do this using a few lines of code:
vowels = 'aeiou' non_list = [] for l in sentence: if not l in vowels: non_list.append(l) nonvowels = ''.join(non_list)
Or you can simplify it by using list generator:
vowels = 'aeiou' nonvowels = ''.join([l for l in sentence if not l in vowels])
This example uses list generator to create a list of letters from the non-vowel letters of the sentence. We then pass the generated list to the join() function to convert to a string.
Fix: As iamadogwhatisthis on reddit suggested, this example doesn't need list generators. It's better to use a generator:
vowels = 'aeiou' nonvowels = ''.join(l for l in sentence if not l in vowels)
Note that the square brackets have been removed. This is because the join function takes any iterable data, including lists or generators. This syntax without square brackets uses generators. This produces the same result (as list generators), as opposed to wrapping all the entries into a list, where the generator produces the corresponding entries as we iterate through them. This saves us from having to store the entire list in memory, and it's more efficient for working with large amounts of data.
7 Getting a list of filenames in a directory
The following code will iterate through the files in the my_dir directory and append each file name with a txt suffix to files.
import os files = [] for f in ('./my_dir'): if ('.txt'): (f)
Again, this can be done using list generators to simplify the code:
import os files = [f for f in ('./my_dir') if ('.txt')]
Or you can fetch a list of relative paths:
import os files = [('./my_dir', f) for f in ('./my_dir') if ('.txt')]
Thanks to rasbt on reddit for this.
8 Reading a csv file as a list of dictionaries
We often need to read and process data from csv files. One of the most useful ways to work with csv data is to convert it into a dictionary list.
import csv data = [] for x in (open('', 'rU')): (x)
You can do this quickly using the list generator style:
import csv data = [ x for x in (open('', 'rU'))]
The DictReader class will automatically use the first line of the csv file as the name of the key attribute of the dictionary. the DictReader class returns an object that will iterate through all the lines of the csv file. This file object is generated by the open() function. We provide two arguments to open() - the first is the csv file name and the second is the schema. In this example, 'rU' has two meanings. As usual, 'r' means to open the file in read mode. The 'U' indicates that we will accept generic line breaks - 'n', 'r' and 'rn'.
Thanks to blacwidonsfw on reddit for this.