0% found this document useful (0 votes)
8 views16 pages

Data Science ASSIGNMENT - 2 E0122048

The document provides a comprehensive list of 50 exercises designed to help users master data structures in Python, including lists, sets, dictionaries, and tuples. Each exercise presents a specific problem to solve, along with context and sample code to illustrate the solution. The exercises range from basic operations to advanced techniques like list and dictionary comprehensions, aiming to enhance understanding and practical skills in Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views16 pages

Data Science ASSIGNMENT - 2 E0122048

The document provides a comprehensive list of 50 exercises designed to help users master data structures in Python, including lists, sets, dictionaries, and tuples. Each exercise presents a specific problem to solve, along with context and sample code to illustrate the solution. The exercises range from basic operations to advanced techniques like list and dictionary comprehensions, aiming to enhance understanding and practical skills in Python programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

50 Best Exercises to Master Data Structure in Python

List Opera ons:

The one Python data structure that you’ll use the most in your code is the Python list. So, it is
essen al to prac ce problems that require using it.

Exercise #1

Problem: Create a list of numbers and find the sum of all elements.

numbers = [1, 2, 3, 4, 5]

total = sum(numbers)
print(total)
Exercise #2

Problem: Remove duplicates from a list and make a unique Python list.

Context: This exercise focuses on u lizing sets to eliminate duplicate elements.

lst = [1, 2, 2, 3, 4, 4, 5]
unique_list = list(set(lst))
print(unique_list)

Exercise #3

Problem: Check if a list is empty.

Context: Understanding how to verify if a list has no elements.

lst = []
print(len(lst) == 0)

Exercise #4

Problem: Reverse a list.

Context: Prac ce reversing the order of elements in a list.

lst = [1, 2, 3, 4, 5]

reversed_list = lst[::-1]
print(reversed_list)
Exercise #5

Problem: Find the index of a specific element in a list.

Context: Learn how to locate the posi on of an element in a list.

Solu on:

lst = ['a', 'b', 'c', 'd']


element = 'c'
index = lst.index(element)
print(index)

Set Opera ons:

It is a data structure that has its concept borrowed from the mathema cal term called the
set. Python set has similar proper es as they are in Maths. So, we can confidently say this about
the sets in Python:

Sets in mathema cs are collec ons of dis nct elements without any specific order. Similarly,
in Python, a set is an unordered collec on of unique elements.

The Coding Mind

Exercise #6

Problem: Perform union and intersec on of two sets.

Context: Understand the concepts of union and intersec on in sets.

set1 = {1, 2, 3}
set2 = {3, 4, 5}

print(set1.union(set2))
print(set1.intersection(set2))

Exercise #7

Problem: Check if a set is a subset of another set.

Context: Prac ce checking whether one set is contained within another.

set1 = {1, 2}
set2 = {1, 2, 3, 4}

print(set1.issubset(set2))
Exercise #8

Problem: Remove an element from a set.

Context: Learn how to eliminate a specific element from a set.

s = {1, 2, 3, 4}

s.discard(3)
print(s)

Exercise #9

Problem: Find the difference between two sets.

Context: Understand how to find elements that exist in one set but not in another.

set1 = {1, 2, 3, 4}

set2 = {3, 4, 5}
print(set1.difference(set2))

Exercise #10

Problem: Check if the two sets have any elements in common.

Context: Determine if there is an intersec on between two sets.

set1 = {1, 2, 3}

set2 = {3, 4, 5}
print(len(set1.intersection(set2)) > 0)
Dic onary Opera ons:

Learning dic onaries in Python is crucial because they help you quickly find informa on using
keys, handle different types of data, and mimic real-life connec ons. Dic onaries are widely
used in Python, making them an essen al tool for problem-solving in various applica ons.

Dic onaries in Python act like real-world dic onaries. They store informa on as key-value pairs,
allowing quick and efficient access to data. Think of a dic onary as a dynamic tool for organizing
and managing informa on in Python. It’s a versa le and essen al feature, making tasks like
retrieval, inser on, and dele on of data a breeze.

Exercise #11

Problem: Create a dic onary and access its values using keys.

Context: Prac ce dic onary crea on and key-based value retrieval.

d = {'name': 'Alice', 'age': 30, 'city': 'New York'}


print(d['age'])

Exercise #12

Problem: Check if a key exists in a dic onary.

Context: Learn how to verify if a specific key is present in a dic onary.

d = {'name': 'Alice', 'age': 30}


print('age' in d)

Exercise #13

Problem: Merge two dic onaries.

Context: Understand how to combine the contents of two dic onaries.

d1 = {'a': 1, 'b': 2}

d2 = {'b': 3, 'c': 4}
merged = {**d1, **d2}
print(merged)
Exercise #14

Problem: Remove a key-value pair from a dic onary.

Context: Prac ce dele ng a specific entry from a dic onary.

d = {'name': 'Alice', 'age': 30, 'city': 'New York'}

del d['city']
print(d)

Exercise #15

Problem: Extract all keys from a dic onary.

Context: Learn how to obtain a list of all keys in a dic onary.

Solu on:

d = {'name': 'Alice', 'age': 30, 'city': 'New York'}


keys = list(d.keys())
print(keys)
Tuple Opera ons:

Tuples in Python are like unchangeable lists. They allow you to store a collec on of items, and
once created, their values cannot be modified. Tuples are handy for situa ons where you want
to ensure data integrity or create a set of values that should stay constant throughout your
program. They’re lightweight, easy to use, and offer a straigh orward way to structure data in
Python.

Learning Python tuples is helpful because they keep data safe from accidental changes, can be
faster in some cases, and work well with func ons that provide mul ple results. They’re handy
when you want stability in your data or when dealing with func ons that use tuples.

Exercise #16

Problem: Create a tuple and perform concatena on.

Context: Prac ce tuple crea on and combining mul ple tuples.

t1 = (1, 2, 3)
t2 = (4, 5)
concatenated = t1 + t2
print(concatenated)
Exercise #17

Problem: Access elements in a tuple using nega ve indexing.

Context: Learn how to retrieve elements from a tuple using nega ve indices.

t = (10, 20, 30, 40)


print(t[-1])
print(t[-3])

Exercise #18

Problem: Find the length of a tuple.

Context: Prac ce obtaining the number of elements in a tuple.

t = (1, 2, 3, 4, 5)
print(len(t))

Exercise #19

Problem: Check if an element exists in a tuple.

Context: Determine if a specific element is present in a tuple.

t = ('a', 'b', 'c')

print('b' in t)
print('x' in t)

Exercise #20

Problem: Convert a tuple to a list.

Context: Understand the process of conver ng a tuple to a list.

t = (1, 2, 3, 4)
lst = list(t)
print(lst)
These exercises cover a range of opera ons on Python data structures, providing a solid
founda on for working with lists, sets, dic onaries, and tuples. Feel free to explore and modify
them to deepen your understanding of Python’s data manipula on capabili es.

Here is the next set of exercises con nuing from Exercise #21 to Exercise #50:

Tuple Opera ons (Con nued):

Exercise #21

Problem: Count the occurrences of an element in a tuple.

Context: Learn how to count the number of mes a specific element appears in a tuple.

t = (1, 2, 2, 3, 2)
print(t.count(2))

Exercise #22

Problem: Create a tuple and find the minimum and maximum values.

Context: Prac ce finding the smallest and largest values in a tuple.

t = (5, 3, 9, 1, 7)

print(min(t))
print(max(t))

Exercise #23

Problem: Check if all elements in a tuple are the same.

Context: Determine whether all elements in a tuple are equal.

t = (4, 4, 4, 4)
print(len(set(t)) == 1)
Exercise #24

Problem: Mul ply all elements in a tuple.

Context: Prac ce performing a mul plica on opera on on all elements of a tuple.

from functools import reduce


import operator
t = (2, 3, 4)
product = reduce(operator.mul, t, 1)
print(product)

Exercise #25

Problem: Create a tuple of strings and concatenate them.

Context: Explore the concatena on of string elements in a tuple.

t = ('Hello', ' ', 'World', '!')


concatenated_strings = ''.join(t)
print(concatenated_strings)

List Comprehension:

Sure, here’s a simple descrip on of list comprehension in Python:

List comprehension in Python is a concise and expressive way to create lists. It allows you to
generate a new list by applying an expression to each item in an exis ng iterable (like a list or
range). This powerful feature enhances code readability and simplifies the process of crea ng
lists, making it a valuable skill for efficient and clean Python programming.

Learning list comprehension in Python is important because it helps you write shorter, clearer,
and more efficient code for crea ng and modifying lists. It’s like a shortcut that makes your
Python programs neater and easier to understand.
Exercise #26

Problem: Generate a list of squares for numbers 1 to 10 using list comprehension.

Context: Prac ce using list comprehension to generate a new list.

numbers = list(range(1, 11))

squares = [n * n for n in numbers]


print(squares)

Exercise #27

Problem: Extract odd numbers from a list using list comprehension.

Context: Learn how to filter elements using list comprehension.

odds = [n for n in numbers if n % 2 != 0]

print(odds)

Exercise #28

Problem: Create a list of tuples with elements and their squares.

Context: Prac ce crea ng tuples and combining them in a list using list comprehension.

tuples = [(n, n * n) for n in numbers]

print(tuples)

Exercise #29

Problem: Fla en a nested list using list comprehension.

Context: Understand how to fla en a list containing nested lists.

nested = [[1, 2], [3, 4], [5, 6]]

flat = [x for sub in nested for x in sub]


print(flat)
Exercise #30

Problem: Create a list excluding even numbers using list comprehension.

Context: Prac ce list comprehension with a condi on to exclude certain elements.

excluded_evens = [n for n in numbers if n % 2 != 0]

print(excluded_evens)

Dic onary Comprehension:

Dic onary comprehension in Python is a quick and neat way to create dic onaries. It lets you
build a new dic onary by specifying key-value pairs using a simple expression applied to each
item in an exis ng collec on. It’s like a shortcut to make your Python code for crea ng
dic onaries shorter and easier to understand.

Learning dic onary comprehension in Python is important because it also helps you write
shorter and clearer code for crea ng dic onaries. It makes your Python programs more efficient
and follows the way Python likes things to be done. It’s like a handy tool to make your code
neater and smarter.

Exercise #31

Problem: Create a dic onary with keys as numbers and values as their squares using dic onary
comprehension.

Context: Prac ce crea ng dic onaries using dic onary comprehension.

dict31 = {i: i**2 for i in range(1, 11)}

print(dict31)

Exercise #32

Problem: Filter a dic onary to exclude keys divisible by 3 using dic onary comprehension.

Context: Understand how to filter keys in a dic onary using comprehension.

dict32 = {k: v for k, v in dict31.items() if k % 3 != 0}

print(dict32)
Exercise #33

Problem: Swap keys and values in a dic onary using dic onary comprehension.

Context: Learn how to exchange keys and values in a dic onary.

dict33 = {v: k for k, v in dict31.items()}

print(dict33)

Exercise #34

Problem: Merge two dic onaries using dic onary comprehension.

Context: Prac ce combining the contents of two dic onaries using comprehension.

d1 = {1: 1, 2: 4}

d2 = {3: 9, 4: 16}
dict34 = {k: v for d in (d1, d2) for k, v in d.items()}
print(dict34)

Exercise #35

Problem: Create a dic onary excluding keys with values less than 3 using dic onary
comprehension.

Context: Prac ce filtering dic onaries based on values using comprehension.

dict35 = {k: v for k, v in dict31.items() if v >= 3}


print(dict35)

Set Comprehension:

Set comprehension in Python is a quick way to create sets. It lets you make a new set by using a
simple expression for each item in an exis ng collec on. It’s like a shortcut to create sets easily
and neatly in Python.

Doing exercises on set comprehension in Python is good because it helps you write code that’s
short and easy to understand. It’s like a handy tool to create unique sets clearly and prac cally,
making your Python programming experience smoother.
Exercise #36

Problem: Create a set of squares for numbers 1 to 5 using set comprehension.

Context: Prac ce using set comprehension to generate a new set.

squares = {i**2 for i in range(1, 6)}

print(squares)

Exercise #37

Problem: Create a set excluding mul ples of 3 using set comprehension.

Context: Understand how to filter elements using set comprehension.

filtered = {i**2 for i in range(1, 6) if i % 3 != 0}

print(filtered)

Exercise #38

Problem: Create a set of common elements between two sets using set comprehension.

Context:

Learn how to find the intersec on of two sets using set comprehension.

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

common = {x for x in set1 if x in set2}


print(common)

Exercise #39

Problem: Create a set of lengths of words in a list using set comprehension.

Context: Prac ce extrac ng lengths of words and crea ng a set using comprehension.

words = ['apple', 'banana', 'cherry', 'date']

lengths = {len(w) for w in words}


print(lengths)
Exercise #40

Problem: Create a set of vowels from a given string using set comprehension.

Context: Understand how to extract specific characters from a string using comprehension.

text = "hello world"

vowels = {c for c in text if c in 'aeiou'}


print(vowels)

Advanced Python Data Structure (List) Exercises:

Doing advanced data structure exercises in Python is great because it helps your coding to get
be er by solving trickier problems. It’s like adding cool tools to your coding toolbox, making
your programming skills stronger and more useful for real-life situa ons.

Exercise #41

Problem: Implement a matrix transposi on using list comprehension.

Context: Prac ce transposing a matrix using nested list comprehension.

matrix = [

[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
transposed = [[row[i] for row in matrix] for i in range(len(matrix[0]))]
print(transposed)

Exercise #42

Problem: Implement a zip opera on on two lists using list comprehension.

Context: Understand how to pair elements from two lists using zip and list comprehension.

list1 = [1, 2, 3]

list2 = ['a', 'b', 'c']


zipped = [(x, y) for x, y in zip(list1, list2)]
print(zipped)
Exercise #43

Problem: Implement a running sum for a list using list comprehension.

Context: Prac ce crea ng a new list with cumula ve sums using list comprehension.

lst = [1, 2, 3, 4, 5]

running_sum = [sum(lst[:i+1]) for i in range(len(lst))]


print(running_sum)

Exercise #44

Problem: Implement a nested list fla ening using list comprehension.

Context: Learn how to fla en a nested list using nested list comprehension.

nested = [[1, 2], [3, 4, 5], [6]]

flat = [x for sub in nested for x in sub]


print(flat)

Exercise #45

Problem: Implement a filter to exclude nega ve numbers from a list using list comprehension.

Context: Prac ce filtering elements based on a condi on using list comprehension.

nums = [-2, -1, 0, 1, 2]

non_negative = [x for x in nums if x >= 0]


print(non_negative)
Advanced Python Data Structure (Dic onary) Exercises:

Solving exercises on advanced dic onary opera ons in Python is useful because it makes your
code work be er, improves your problem-solving skills, and helps you handle real-world data
situa ons more effec vely. It’s like adding powerful tools to your coding skills.

Exercise #46

Problem: Merge two dic onaries and sum values for common keys.

Context: Prac ce merging dic onaries and performing opera ons on common keys.

d1 = {'a': 1, 'b': 2, 'c': 3}

d2 = {'b': 3, 'c': 4, 'd': 5}


merged_sum = {k: d1.get(k, 0) + d2.get(k, 0) for k in set(d1) | set(d2)}
print(merged_sum)

Exercise #47

Problem: Group a list of tuples by the first element using dic onary comprehension.

Context: Understand how to group elements in a list of tuples using dic onary comprehension.

tuples = [('x', 1), ('y', 2), ('x', 3), ('z', 4)]

grouped = {k: [v for t, v in tuples if t == k] for k in {t for t, _ in tuples}}


print(grouped)

Exercise #48

Problem: Extract unique elements and their counts from a list using dic onary comprehension.

Context: Prac ce crea ng a dic onary with unique elements and their counts using
comprehension.

items = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']

counts = {x: items.count(x) for x in set(items)}


print(counts)
Exercise #49

Problem: Find common keys in two dic onaries using dic onary comprehension.

Context: Learn how to find common keys in two dic onaries using comprehension.

d1 = {'a': 1, 'b': 2, 'c': 3}

d2 = {'b': 20, 'c': 30, 'd': 40}


common = {k: d1[k] for k in d1 if k in d2}
print(common)

Exercise #50

Problem: Create a dic onary from two lists using dic onary comprehension.

Context: Prac ce crea ng a dic onary from two parallel lists using comprehension.

keys = ['name', 'age', 'city']

values = ['Alice', 30, 'London']


combined = {keys[i]: values[i] for i in range(len(keys))}
print(combined)

You might also like