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

Python 2

The document provides a comprehensive guide on working with dictionaries, lists, and tuples in Python, including creating, accessing, updating, and manipulating these data structures. Each section includes problems, code examples, and explanations of the underlying concepts. The content is structured into 20 distinct problems for each data type, demonstrating various operations and techniques.
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 views34 pages

Python 2

The document provides a comprehensive guide on working with dictionaries, lists, and tuples in Python, including creating, accessing, updating, and manipulating these data structures. Each section includes problems, code examples, and explanations of the underlying concepts. The content is structured into 20 distinct problems for each data type, demonstrating various operations and techniques.
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

dictionary

1. Create a Dictionary
Problem

Create a dictionary with keys as names and values as marks.

Code
def create_dict():
d = {'Alice': 85, 'Bob': 90, 'Charlie': 78}
return d

print(create_dict())

Explanation

 Dictionary stores key-value pairs


 Keys must be unique

2. Access Dictionary Elements


Problem

Access the value of a given key safely.

Code
def access_value(d, key):
return [Link](key, "Key not found")

print(access_value({'a': 1, 'b': 2}, 'a'))

Explanation

 .get() avoids errors if key is missing

3. Update Dictionary Value


Problem

Update value of a specific key.


Code
def update_value(d, key, value):
d[key] = value
return d

print(update_value({'a': 1}, 'a', 10))

Explanation

 Direct assignment updates value

4. Delete a Key
Problem

Remove a key from dictionary.

Code
def delete_key(d, key):
[Link](key, None)
return d

print(delete_key({'a':1,'b':2}, 'b'))

Explanation

 .pop() removes key safely

5. Check Key Existence


Problem

Check if key exists in dictionary.

Code
def check_key(d, key):
return key in d

print(check_key({'a':1,'b':2}, 'a'))

Explanation
 in operator checks existence

6. Iterate Through Dictionary


Problem

Print all key-value pairs.

Code
def iterate_dict(d):
for k, v in [Link]():
print(k, v)

iterate_dict({'a':1,'b':2})

Explanation

 .items() returns pairs

7. Count Frequency of Elements


Problem

Count frequency of elements in a list using dictionary.

Code
def frequency(lst):
freq = {}
for item in lst:
freq[item] = [Link](item, 0) + 1
return freq

print(frequency([1,2,2,3,1,1]))

Explanation

 .get() handles missing keys

8. Merge Two Dictionaries


Problem

Merge two dictionaries.

Code
def merge_dict(d1, d2):
return {**d1, **d2}

print(merge_dict({'a':1}, {'b':2}))

Explanation

 ** unpacks dictionaries

9. Find Maximum Value Key


Problem

Find key with highest value.

Code
def max_key(d):
return max(d, key=[Link])

print(max_key({'a':5,'b':10,'c':7}))

Explanation

 [Link] used for comparison

10. Sort Dictionary by Value


Problem

Sort dictionary based on values.

Code
def sort_dict(d):
return dict(sorted([Link](), key=lambda x: x[1]))

print(sort_dict({'a':3,'b':1,'c':2}))
Explanation

 Lambda extracts values

11. Remove Duplicate Values


Problem

Remove duplicate values.

Code
def remove_duplicates(d):
seen = set()
result = {}
for k, v in [Link]():
if v not in seen:
result[k] = v
[Link](v)
return result

print(remove_duplicates({'a':1,'b':2,'c':1}))

Explanation

 Uses set to track duplicates

12. Dictionary from Two Lists


Problem

Create dictionary using two lists.

Code
def create_from_lists(keys, values):
return dict(zip(keys, values))

print(create_from_lists(['a','b'], [1,2]))

Explanation

 zip() pairs elements


13. Nested Dictionary Access
Problem

Access nested dictionary value.

Code
def nested_access(d):
return d['student']['marks']

data = {'student': {'marks': 90}}


print(nested_access(data))

Explanation

 Access step-by-step

14. Sum of Values


Problem

Find sum of all values.

Code
def sum_values(d):
return sum([Link]())

print(sum_values({'a':10,'b':20}))

Explanation

 .values() gives all values

15. Invert Dictionary


Problem

Swap keys and values.

Code
def invert_dict(d):
return {v: k for k, v in [Link]()}

print(invert_dict({'a':1,'b':2}))

Explanation

 Dictionary comprehension

16. Filter Dictionary


Problem

Filter values greater than 10.

Code
def filter_dict(d):
return {k:v for k,v in [Link]() if v > 10}

print(filter_dict({'a':5,'b':15,'c':20}))

Explanation

 Conditional comprehension

17. Count Keys


Problem

Find number of keys.

Code
def count_keys(d):
return len(d)

print(count_keys({'a':1,'b':2}))

Explanation

 len() returns number of keys


18. Common Keys Between Dictionaries
Problem

Find common keys.

Code
def common_keys(d1, d2):
return [Link]() & [Link]()

print(common_keys({'a':1,'b':2}, {'b':3,'c':4}))

Explanation

 Set intersection

19. Default Value Handling


Problem

Assign default value if key missing.

Code
def default_dict(d, key):
return [Link](key, 0)

data = {'a':1}
print(default_dict(data, 'b'))
print(data)

Explanation

 setdefault() inserts if missing

20. Group Values by Key Pattern


Problem

Group words by first letter.

Code
def group_words(words):
result = {}
for word in words:
key = word[0]
[Link](key, []).append(word)
return result

print(group_words(['apple','banana','apricot']))

Explanation

 Groups based on first character

list
1. Create and Access List
Problem

Create a list and access elements by index.

Code
def create_list():
lst = [10, 20, 30, 40]
return lst[0], lst[-1]

print(create_list())

Explanation

 Lists are ordered and mutable


 Indexing:
o 0 → first element
o -1 → last element

2. Add Elements to List


Problem

Add elements using append() and insert().

Code
def add_elements(lst):
[Link](50)
[Link](1, 15)
return lst

print(add_elements([10, 20, 30]))

Explanation

 append() → adds at end


 insert(index, value) → adds at position

3. Remove Elements
Problem

Remove elements from a list.

Code
def remove_elements(lst):
[Link](20)
[Link]()
return lst

print(remove_elements([10, 20, 30, 40]))

Explanation

 remove() → removes by value


 pop() → removes last element

4. Find Maximum and Minimum


Problem

Find max and min in list.

Code
def find_max_min(lst):
return max(lst), min(lst)

print(find_max_min([5, 2, 9, 1]))

Explanation

 Built-in functions simplify computation


5. Sum and Average
Problem

Calculate sum and average.

Code
def sum_avg(lst):
total = sum(lst)
avg = total / len(lst)
return total, avg

print(sum_avg([10, 20, 30]))

Explanation

 sum() computes total


 Average = total / count

6. Reverse List
Problem

Reverse a list.

Code
def reverse_list(lst):
return lst[::-1]

print(reverse_list([1,2,3,4]))

Explanation

 Slicing [::-1] reverses list

7. Remove Duplicates
Problem

Remove duplicate elements.


Code
def remove_duplicates(lst):
return list(set(lst))

print(remove_duplicates([1,2,2,3,1]))

Explanation

 set()removes duplicates
 Converted back to list

8. Sort List
Problem

Sort list in ascending and descending order.

Code
def sort_list(lst):
return sorted(lst), sorted(lst, reverse=True)

print(sort_list([5,1,4,2]))

Explanation

 sorted() returns new list


 reverse=True → descending

9. List Comprehension (Square Numbers)


Problem

Square all elements.

Code
def square_list(lst):
return [x**2 for x in lst]

print(square_list([1,2,3]))

Explanation
 Compact syntax for transformations

10. Filter Even Numbers


Problem

Extract even numbers.

Code
def even_numbers(lst):
return [x for x in lst if x % 2 == 0]

print(even_numbers([1,2,3,4,5]))

Explanation

 Condition inside comprehension

11. Merge Two Lists


Problem

Merge two lists.

Code
def merge_lists(l1, l2):
return l1 + l2

print(merge_lists([1,2], [3,4]))

Explanation

 + concatenates lists

12. Find Common Elements


Problem

Find common elements between lists.


Code
def common_elements(l1, l2):
return list(set(l1) & set(l2))

print(common_elements([1,2,3], [2,3,4]))

Explanation

 Uses set intersection

13. Flatten Nested List


Problem

Flatten a 2D list.

Code
def flatten(lst):
return [item for sublist in lst for item in sublist]

print(flatten([[1,2],[3,4]]))

Explanation

 Nested comprehension

14. Count Frequency


Problem

Count frequency of elements.

Code
def frequency(lst):
freq = {}
for x in lst:
freq[x] = [Link](x, 0) + 1
return freq

print(frequency([1,2,2,3,1]))

Explanation
 Uses dictionary for counting

15. Find Second Largest


Problem

Find second largest number.

Code
def second_largest(lst):
lst = list(set(lst))
[Link]()
return lst[-2]

print(second_largest([10, 20, 4, 45, 99]))

Explanation

 Removes duplicates
 Sorts and selects second last

16. Rotate List


Problem

Rotate list by k positions.

Code
def rotate(lst, k):
return lst[k:] + lst[:k]

print(rotate([1,2,3,4,5], 2))

Explanation

 Uses slicing

17. Check Palindrome List


Problem
Check if list is palindrome.

Code
def is_palindrome(lst):
return lst == lst[::-1]

print(is_palindrome([1,2,3,2,1]))

Explanation

 Compare with reversed list

18. Find Missing Number


Problem

Find missing number in sequence.

Code
def missing_number(lst):
n = len(lst) + 1
total = n * (n + 1) // 2
return total - sum(lst)

print(missing_number([1,2,4,5]))

Explanation

 Uses formula for sum of n numbers

19. Split List into Chunks


Problem

Split list into chunks of size k.

Code
def chunk_list(lst, k):
return [lst[i:i+k] for i in range(0, len(lst), k)]

print(chunk_list([1,2,3,4,5,6], 2))
Explanation

 Uses slicing in loop

20. Find All Pairs with Given Sum


Problem

Find pairs whose sum equals target.

Code
def find_pairs(lst, target):
result = []
for i in range(len(lst)):
for j in range(i+1, len(lst)):
if lst[i] + lst[j] == target:
[Link]((lst[i], lst[j]))
return result

print(find_pairs([1,2,3,4,5], 5))

Explanation

 Nested loops check all combinations

TUPLE
Create and Access Tuple
Problem

Create a tuple and access elements.

Code
def create_tuple():
t = (10, 20, 30, 40)
return t[0], t[-1]

print(create_tuple())

Explanation

 Tuples are ordered and immutable


 Access using indexing (0, -1)
2. Tuple Packing and Unpacking
Problem

Pack values into a tuple and unpack them.

Code
def unpack_tuple():
t = (1, 2, 3)
a, b, c = t
return a, b, c

print(unpack_tuple())

Explanation

 Packing → storing multiple values


 Unpacking → assigning values to variables

3. Count and Index


Problem

Count occurrences and find index of element.

Code
def count_index(t):
return [Link](2), [Link](2)

print(count_index((1,2,3,2,4)))

Explanation

 count() → frequency
 index() → first occurrence

4. Convert List to Tuple


Problem
Convert a list into tuple.

Code
def list_to_tuple(lst):
return tuple(lst)

print(list_to_tuple([1,2,3]))

Explanation

 tuple() constructor used

5. Concatenate Tuples
Problem

Merge two tuples.

Code
def merge_tuple(t1, t2):
return t1 + t2

print(merge_tuple((1,2), (3,4)))

Explanation

 + operator concatenates tuples

6. Find Maximum and Minimum


Problem

Find max and min in tuple.

Code
def max_min(t):
return max(t), min(t)

print(max_min((5,1,9,2)))

Explanation
 Built-in functions work on tuples

7. Slice a Tuple
Problem

Extract subset of tuple.

Code
def slice_tuple(t):
return t[1:4]

print(slice_tuple((10,20,30,40,50)))

Explanation

 Slicing works like lists

8. Reverse Tuple
Problem

Reverse a tuple.

Code
def reverse_tuple(t):
return t[::-1]

print(reverse_tuple((1,2,3,4)))

Explanation

 Slicing [::-1] reverses

9. Check Element Exists


Problem

Check if element exists in tuple.


Code
def check_element(t, x):
return x in t

print(check_element((1,2,3), 2))

Explanation

 in operator checks presence

10. Remove Element (Convert Method)


Problem

Remove element from tuple.

Code
def remove_element(t, x):
lst = list(t)
[Link](x)
return tuple(lst)

print(remove_element((1,2,3,4), 2))

Explanation

 Tuples are immutable → convert to list

11. Nested Tuple Access


Problem

Access element in nested tuple.

Code
def nested_access(t):
return t[1][1]

print(nested_access((1, (2, 3), 4)))

Explanation
 Use multiple indexing

12. Count Frequency of Elements


Problem

Count frequency using dictionary.

Code
def frequency(t):
freq = {}
for x in t:
freq[x] = [Link](x, 0) + 1
return freq

print(frequency((1,2,2,3,1)))

Explanation

 Uses dictionary for counting

13. Find Duplicate Elements


Problem

Find duplicate values in tuple.

Code
def duplicates(t):
return [x for x in set(t) if [Link](x) > 1]

print(duplicates((1,2,2,3,1)))

Explanation

 Uses count() to detect duplicates

14. Flatten Nested Tuple


Problem
Flatten a nested tuple.

Code
def flatten(t):
result = []
for item in t:
if isinstance(item, tuple):
[Link](item)
else:
[Link](item)
return tuple(result)

print(flatten((1,(2,3),(4,5))))

Explanation

 Checks nested structure


 Extends elements

15. Swap Elements


Problem

Swap first and last elements.

Code
def swap_tuple(t):
lst = list(t)
lst[0], lst[-1] = lst[-1], lst[0]
return tuple(lst)

print(swap_tuple((1,2,3,4)))

Explanation

 Convert to list for modification

16. Find Length of Tuple


Problem

Find number of elements.

Code
def tuple_length(t):
return len(t)

print(tuple_length((1,2,3)))

Explanation

 len() returns size

17. Tuple of Squares


Problem

Create tuple of squares.

Code
def square_tuple(t):
return tuple(x**2 for x in t)

print(square_tuple((1,2,3)))

Explanation

 Uses generator expression

18. Zip Two Tuples


Problem

Combine two tuples into pairs.

Code
def zip_tuple(t1, t2):
return tuple(zip(t1, t2))

print(zip_tuple((1,2), (3,4)))

Explanation

 zip() pairs elements


19. Find Second Largest Element
Problem

Find second largest value.

Code
def second_largest(t):
t = tuple(set(t))
t = sorted(t)
return t[-2]

print(second_largest((10,20,4,45,99)))

Explanation

 Remove duplicates → sort → pick second last

20. Check Palindrome Tuple


Problem

Check if tuple is palindrome.

Code
def is_palindrome(t):
return t == t[::-1]

print(is_palindrome((1,2,3,2,1)))

Explanation

 Compare tuple with reversed version

STRING

1. Create and Access String


Problem

Create a string and access characters.

Code
def access_string():
s = "Python"
return s[0], s[-1]

print(access_string())

Explanation

 Strings are immutable sequences


 Indexing:
o 0 → first character
o -1 → last character

2. String Length
Problem

Find length of a string.

Code
def string_length(s):
return len(s)

print(string_length("Hello"))

Explanation

 len() returns total characters

3. Convert Case
Problem

Convert string to upper and lower case.

Code
def change_case(s):
return [Link](), [Link]()

print(change_case("Python"))

Explanation
 .upper() → uppercase
 .lower() → lowercase

4. Reverse String
Problem

Reverse a string.

Code
def reverse_string(s):
return s[::-1]

print(reverse_string("hello"))

Explanation

 Slicing [::-1] reverses string

5. Check Palindrome
Problem

Check if string is palindrome.

Code
def is_palindrome(s):
return s == s[::-1]

print(is_palindrome("madam"))

Explanation

 Compare string with reversed version

6. Count Vowels
Problem
Count number of vowels.

Code
def count_vowels(s):
vowels = "aeiouAEIOU"
count = 0
for char in s:
if char in vowels:
count += 1
return count

print(count_vowels("Hello World"))

Explanation

 Iterates through characters


 Checks membership

7. Remove Spaces
Problem

Remove all spaces from string.

Code
def remove_spaces(s):
return [Link](" ", "")

print(remove_spaces("Hello World"))

Explanation

 .replace() removes spaces

8. Count Words
Problem

Count number of words.

Code
def count_words(s):
return len([Link]())
print(count_words("Python is easy"))

Explanation

 .split() divides string into words

9. Find Frequency of Characters


Problem

Count frequency of each character.

Code
def char_frequency(s):
freq = {}
for ch in s:
freq[ch] = [Link](ch, 0) + 1
return freq

print(char_frequency("hello"))

Explanation

 Uses dictionary for counting

10. Check Anagram


Problem

Check if two strings are anagrams.

Code
def is_anagram(s1, s2):
return sorted(s1) == sorted(s2)

print(is_anagram("listen", "silent"))

Explanation

 Sort both strings


 Compare equality
11. Find Substring
Problem

Check if substring exists.

Code
def find_substring(s, sub):
return sub in s

print(find_substring("Python programming", "prog"))

Explanation

 in checks substring

12. Replace Characters


Problem

Replace all occurrences of a character.

Code
def replace_char(s):
return [Link]('a', '@')

print(replace_char("banana"))

Explanation

 Replaces all 'a' with '@'

13. Capitalize Each Word


Problem

Capitalize first letter of each word.

Code
def capitalize_words(s):
return [Link]()

print(capitalize_words("hello world"))

Explanation

 .title() capitalizes words

14. Remove Duplicates


Problem

Remove duplicate characters.

Code
def remove_duplicates(s):
return "".join([Link](s))

print(remove_duplicates("programming"))

Explanation

 [Link]() preserves order

15. Find Maximum Occurring Character


Problem

Find most frequent character.

Code
def max_char(s):
freq = {}
for ch in s:
freq[ch] = [Link](ch, 0) + 1
return max(freq, key=[Link])

print(max_char("banana"))

Explanation

 Uses dictionary + max()


16. Check Digit String
Problem

Check if string contains only digits.

Code
def is_digit(s):
return [Link]()

print(is_digit("12345"))

Explanation

 .isdigit() checks numeric string

17. Join List into String


Problem

Convert list into string.

Code
def join_list(lst):
return " ".join(lst)

print(join_list(["Python", "is", "fun"]))

Explanation

 .join() combines list elements

18. Find Longest Word


Problem

Find longest word in string.

Code
def longest_word(s):
words = [Link]()
return max(words, key=len)

print(longest_word("Python is very powerful"))

Explanation

 Uses max() with length

19. Count Specific Character


Problem

Count occurrences of a specific character.

Code
def count_char(s, ch):
return [Link](ch)

print(count_char("banana", 'a'))

Explanation

 .count() counts occurrences

20. Remove Punctuation


Problem

Remove punctuation from string.

Code
import string

def remove_punctuation(s):
return "".join(ch for ch in s if ch not in [Link])

print(remove_punctuation("Hello, World!"))

Explanation

 Uses [Link]
 Filters unwanted characters

You might also like