LIST COMPREHENSION
even_numbers = [x for x in range(5) if x % 2 == 0]
set doesnt allow duplicated values
compare:
[1]pairs = [(x, y) for x in range(2) for y in range(3)]
and
[2]pairs=[]
for x in range(2): #[0 1]
for y in range(3): #[0 1 2]
pairs.append((x,y))
print(pairs)
=> [1] Run faster
List comprehension doesn't have else in if argument
**IMPORTANT:**
- Code Reducability: code needs to be understandable and clean
If having more than 3 for loop => don't use list comprehension => code can be looked at one time
- Remember, every list comprehension can be rewritten in for loop, but every for loop can’t be rewritten in the form of list comprehension.
**GENERATOR**
only return a value at once to save memory
**ITERATOR**
An iterator is an object that can be iterated upon, meaning that you can traverse through all the values. Right now, you can just identify something as an iterator when you can loop through it
range, tuple, list, set, string, dict, dict view object(keys, values, items)
**IMPORTED FUNCTIONS**
- random.random (Return the next random floating point number in the range [0.0, 1.0).) ( 0.0 is possible, but all returned numbers will be strictly less than 1.0.)
- random.randrange(start, stop[, step]) => return different values within the pre-defined range every time it runs
- random.seed():
example: random.seed(10)
print(random.random())
- random.shuffle (seq): Shuffle the sequence seq in place
- random.choice(seq): Return a random element from the non-empty sequence seq
- random.sample(population, k, *, counts=None)
- ZIP: In a sense, zip is a sort of generator, and it only generates value upon request => zip(list1,list2)
+ To print all the pairs in the zipped list:
=> for pair in zip(list1, list2):
print(pair)
+ To print only a pair:
=> next(tmp)
+ If the lists are different lengths, zip stops as soon as the first list ends.
+ To separate resulted lists after 3 different lists' elements are zipped =>
list1 = ['a', 1, True]
list2 = ['b', 2, False]
list3 = ['c', 3, True]
list_of_word,list_of_number,list_of_bool = zip(list1,list2,list3)