List
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
>>> a = [66.25, 333, 333, 1, 1234.5] >>> print(a.count(333), a.count(66.25), a.count('x')) 2 1 0 >>> a.insert(2, -1) >>> a.append(333) >>> a [66.25, 333, -1, 333, 1, 1234.5, 333] >>> a.index(333) 1 >>> a.remove(333) >>> a [66.25, -1, 333, 1, 1234.5, 333] >>> a.reverse() >>> a [333, 1234.5, 1, 333, -1, 66.25] >>> a.sort() >>> a [-1, 1, 66.25, 333, 333, 1234.5] >>> a.pop() 1234.5 >>> a [-1, 1, 66.25, 333, 333] |
You can use list to implement stack (ie. LIFO). For that, we can use:
- append to add to the end of the list
- pop to remove from the front of the list.
List comprehension (LC)
It is syntactic sugar that transforms one list (any iterable actually) into another list. During this process, elements can be filtered and transformed if needed. In term of performance, LC actually runs faster.
General form:
[ expression for item in list if conditional ]- expression can use the variable item
- there can be nested for loop sequencing in order
- if-condition is the filter
List comprehension examples
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
""" S = {x² : x in {0 ... 9}} V = (1, 2, 4, 8, ..., 2¹²) M = {x | x in S and x even} """ # example 1: Simple basic usage referencing what we want to do above S = [x**2 for x in range(10)] V = [2**i for i in range(13)] M = [x for x in S if x % 2 == 0] # example 2: Flatten matrix LC vs expanded form flattened = [n for row in matrix for n in row] flattened = [] for row in matrix: for n in row: flattened.append(n) # example 3: create list within list words = 'The quick brown fox jumps over the lazy dog'.split() stuff = [[w.upper(), w.lower(), len(w)] for w in words] # example 4: expression on 2 lists newList = [x+y for x in [10,30,50] for y in [20,40,60]] print(newList) >> [30, 50, 70, 50, 70, 90, 70, 90, 110] # example 5: cross product of 2 sets colours = [ "red", "green", "yellow", "blue" ] things = [ "house", "car", "tree" ] coloured_things = [ (x,y) for x in colours for y in things ] >>> print coloured_things [('red', 'house'), ('red', 'car'), ('red', 'tree'), ('green', 'house'), ('green', 'car'), ('green', 'tree'), ('yellow', 'house'), ('yellow', 'car'), ('yellow', 'tree'), ('blue', 'house'), ('blue', 'car'), ('blue', 'tree')] ## example 6: transposition matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] transposeMatrix = [[row[i] for row in matrix] for i in range(4)] print(transposeMatrix) >>> [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] |
Set and dictionary comprehension
1 2 3 4 5 6 7 8 9 10 11 |
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] print(basket) basketSet = {fruit for fruit in basket} print(basketSet) basketCounterDict = {fruit: basket.count(fruit) for fruit in basket} print(basketCounterDict) |
Connect with us