We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
4 ee
eer iy
01 Enumerate for Index-Value Pairs
Use enumerate() to iterate over a sequence while
keeping track of the index.
Pa
some_list = ['a', 'b', 'c']
PC eee (some_list) :
(index, value)
02 List Unpacking with *
You can use the * operator to unpack elements from
a list or tuple into individual variables.
SMe cone}
first, second, *rest = [1, 2, 3, 4, 5]
(first, second, rest)
# Output: 12 [3, 4, 5]3 List Comprehension with Conditional Logic
Use list comprehensions with conditional logic to create
more concise and readable lists.
List Comprehension
COCs eed x (10) x% 2 = 06)
(even_numbers) # Output: [0, 2, 4, 6, 8]
04 Dictionary Comprehension
Similar to list comprehensions, you can create dictionaries
with dictionary comprehensions.
Cen Wee neue
squared_dict = {x: x#«2
(CTE mr tao)
# Output: (0: 6, 4: 1, 205 Unpacking Unknown Number of Elements
You can use the * operator to collect an unknown number
of elements into a list/tuple.
Ceo
*rest, last = [1
fixst:", first)
rest:", rest)
last:", last)
06 Using any() and all() for Iterables
any() returns True if at least one element is True in an
iterable; all() returns True if all elements are True
CO ee
CMe ee TCRT ESD)
(ead aet net aero)07 Underscore (_) for Ignoring Values
You can use an underscore _ to ignore values in
unpacking when you don't need them.
ea eR
first, _, third = [1, 2, 3]
(first, third) # Output: 1 3
08 Using timeit for Code Timing
You can use the timeit module to measure the execution
time of code snippets.
eset cy
eursed
Cm
sum({x fox x in xange(1909000)])
Crna tims Meas Rees rad me me
execution_time:.5f} se09 ‘collections.Counter' for Counting Elements
The Counter class from the collec
tions module makes it
easy to count occurrences of elements in a sequence.
etn
Carre Cy ort
atajal eects ses, any ay, 4]
aCrTeD)
(counter) # outp
Pers eer
Comes eC eers
10 Using random.choice() for Random Selection
Use random.choic'
a sequence
Gene ele
Poor
eae aE
pen Umer tae LL)
(random_fruit)
rs iis money
() to randomly select an element from
Patras