python -c "print(set([1,1,4,5,6,2,2,4,3,5]))"
set()
denoted by {}
is a list of unique elements. When a list is converted into
a set all the repeated values are discarded.
python -c "import collections;print(collections.Counter([1,2,2,3,3,4,4,4,4,4,6,6,6,6,6,6,6,6,6,7]))"
collections.Counter
will take the list and creates a list of dictionary as [{<item>: <frequency of item in the list>}, ...]
python -c "import collections;x=dict(collections.Counter([1,2,3,4,5,5,6,6,6,7]));print([k for k,v in x.items() if v>1])"
Return only those items in the list that are repeated.
collections.Counter
will take the list and creates a list of dictionary as [{<item>: <frequency of item in the list>}, ...]
[k for k,v in x.items() if v>1]
creates a new list with the items that are occurred more than ones in the list.
python -c "x=[1,2,3,4,5,6,7,8,9];print(x[::-1])"
x[::-1]
is used to slicing a list. Negative value creates a copy of the list in reverse order.
python -c "import itertools;print(list(itertools.permutations(range(1,4))))"
itertools.permutations()
generates all the possible permutations of the given list.
python -c "import itertools;print([list(itertools.combinations([1,2,3], x)) for x in range(len([1,2,3])+1)])"
itertools.combinations()
generates all the possible combinations of a given list.
It take another optional argument, r
represents number of items per combination.
python -c "y={1: 6, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1};print(dict(sorted(y.items())))"
Sorts the dict by key.
sorted()
is python's in-built method to sorting iterables.
By default, dictionaries are sorted by key.
python -c "y={1: 6, 2: 5, 3: 4, 4: 3, 5: 2, 6: 1};print(dict(sorted(y.items(), key=lambda kv: kv[1])))"
Sorts the dict by value. sorted()
takes an optional keyword argument key
which take a callable
to specify search key. In this case the search key is dict value instead of dict key.
python -c "import itertools;print(list(itertools.product([['x','y','z'],[1,2,3]])))"
Generates cartesian product of two lists.