Data Science
DAI-101 Spring 2024-25
Dr. Devesh Bhimsaria
Office: F9, Old Building
Department of Biosciences and Bioengineering
Indian Institute of Technology–Roorkee
devesh.bhimsaria@bt.iitr.ac.in
Dr. Devesh Bhimsaria 1
Python challenges
Loops
i = 0
while True :
i += 1
if i == 5 :
continue
print (i)
if i > 10 :
break
Dr. Devesh Bhimsaria 3
Loops
i = 0
while True :
if i == 5 :
continue
print (i)
if i > 10 :
break
i += 1
Dr. Devesh Bhimsaria 4
Single line code challenge
Python challenge
⚫ Python code to print a string with gaps as | 0 to 8
⚫ Output should be following without using loops and
writing 0 to 8
0|1|2|3|4|5|6|7|8
print('|'.join((map(str,list(range(9))))))
Dr. Devesh Bhimsaria 6
Reverse a String
⚫ Print the reverse of the string "Python" in one line of
code.
⚫ print("Python"[::-1])
Dr. Devesh Bhimsaria 7
Print Even Numbers from a List
⚫ Print all even numbers from the list [1, 2, 3, 4, 5, 6,
7, 8, 9] in one line
⚫ print([x for x in range(1,10) if x % 2 == 0])
Dr. Devesh Bhimsaria 8
Flatten a Nested List
⚫ Flatten the list [[1, 2], [3, 4], [5, 6]] in one line.
⚫ print([x for sublist in [[1, 2], [3, 4], [5, 6]] for x in
sublist])
Dr. Devesh Bhimsaria 9
Count Vowels in a String
⚫ Count the number of vowels in the string "Hello
World" in one line.
⚫ print(sum(1 for char in "Hello World" if char.lower()
in "aeiou"))
Dr. Devesh Bhimsaria 10
Remove duplicates from a list
⚫ Remove duplicates from the list [1, 2, 2, 3, 4, 4, 5] in
one line.
⚫ print(list(set([1, 2, 2, 3, 4, 4, 5])))
Dr. Devesh Bhimsaria 11
Generate Squares of Numbers
⚫ Generate a list of squares of numbers from 1 to 10 in
one line.
⚫ print([x**2 for x in range(1, 11)])
Dr. Devesh Bhimsaria 12
Swap variables
⚫ Swap the values of a and b in one line.
⚫ a, b = b, a
Dr. Devesh Bhimsaria 13
Check Prime Number
⚫ Write a one-liner to check if x is a prime number.
⚫ x=29
⚫ all() function returns True if all items in an iterable
are true
⚫ print(all(x % i != 0 for i in range(2, int(x**0.5) +
1)))
Dr. Devesh Bhimsaria 14
Create a Dictionary from Two Lists
⚫ Create a dictionary from the lists ['a', 'b', 'c'] and [1,
2, 3] in one line.
⚫ The zip() function returns a zip object, which is an
iterator of tuples where the first item in each passed
iterator is paired together, and then the second item
in each passed iterator are paired together etc.
⚫ print(dict(zip(['a', 'b', 'c'], [1, 2, 3])))
Dr. Devesh Bhimsaria 15
Sort a List of Tuples by Second Element
⚫ Sort the list of tuples [(1, 3), (4, 1), (2, 2)] by their
second element in one line.
⚫ sorted([(1, 3), (4, 1), (2, 2)], key=lambda x: x[1])
Dr. Devesh Bhimsaria 16
Thank You
• All my slides/notes excluding third party material
are licensed by various authors including myself
under https://creativecommons.org/licenses/by-
nc/4.0/
Dr. Devesh Bhimsaria 17