Builtin Functions
Zip Function
Takes iterables (lists, dictionaries, tuples, strings, etc) and zips them into tuples
used for parallel iteration
Return a zip object, which is an iterator of tuples
countries = ["America", "Australia", "England"]
cities = ["New York", "Sydney", "London"]
countries_and_cities = zip(countries,capitals)
countries_and_capitals.__next__() # can only call once, if need it more than one, need to reinitializeZip will base on shortest iterables, to change it to base on longest one, use zip_longest
from itertools import zip_longest
countries = ["America", "Australia", "England", "France"]
cities = ["New York", "Sydney", "London"]
countries_and_cities = zip_longest(countries,capitals) # value will be None
countries_and_cities = zip_longest(countries,capitals, fillvalue="Fill when None")Enumerate Function
Add a counter to an iterable and returns it as an enumerate object
The enumerate object is usually used in for loops
Lambda Function
Also called anonymous functions because they are unnamed
Syntax: lambda arguments: expression
can take any number of parameters
Sort and Sorted Function
sort method only works for list
sorted function works for any iterable
If number is store as string it, sort will not sort it numerically
use $list.sort(key=int)
or $list.append(int(input)) to change individual item to integer
Map function
Applies a given function to each item of an iterable
Returns a map object (which is an iterator)
Shouuld be used instead of loop when possible
Filter Function
Contructs an iterator from elements of an iterable for which a function return True. In other words, it filters an iterable based on a condition given by a function
Any and All Function
Any
Return True if any of the elements of the iterable is True and False otherwise
At least one value is True -> True
All values are False -> False
Empty iterable -> False
All
Return True if all elements of the iterable is True and False otherwise
At least one value is False -> False
All values are True -> True
Empty iterable -> True
Iterators
An iterable is a representation of a series of elements that can be iterated over. It does not have any state such as a "current element". But every iterable can be converted to an iterator by using iter()
An iterator is the object with iteration state. It can be checked to see if there're more elements using the next() or next() and move to the next element
Last updated