[go: up one dir, main page]

0% found this document useful (0 votes)
4 views9 pages

Module 1

The document provides a comprehensive overview of Python lists, including methods for inserting and deleting items, negative indexing, slicing, and various list operations. It also compares lists with dictionaries and tuples, discusses dictionary methods, and presents several programming examples for manipulating strings and lists. Additionally, it covers statistical calculations and basic game board printing in Python.

Uploaded by

Avani Shetty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views9 pages

Module 1

The document provides a comprehensive overview of Python lists, including methods for inserting and deleting items, negative indexing, slicing, and various list operations. It also compares lists with dictionaries and tuples, discusses dictionary methods, and presents several programming examples for manipulating strings and lists. Additionally, it covers statistical calculations and basic game board printing in Python.

Uploaded by

Avani Shetty
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

MODULE 2

1. What is a list? Explain the methods used to insert and delete items from the list.

Answer:
A list in Python is an ordered, mutable collection of elements enclosed in square brackets [].

Methods to Insert Items:

1. append(x) – Adds x at the end.

lst = [1, 2, 3]

lst.append(4) # [1, 2, 3, 4]

2. insert(i, x) – Inserts x at index i.

lst.insert(1, 5) # [1, 5, 2, 3, 4]

3. extend(iterable) – Adds multiple elements.

lst.extend([6, 7]) # [1, 5, 2, 3, 4, 6, 7]

Methods to Delete Items:

1. remove(x) – Removes first occurrence of x.

lst.remove(2) # [1, 5, 3, 4, 6, 7]

2. pop([i]) – Removes and returns item at index i (default last).

lst.pop(1) # Removes 5 → [1, 3, 4, 6, 7]

3. del statement – Deletes an element or slice.

del lst[0] # [3, 4, 6, 7]

4. clear() – Empties the list.

lst.clear() # []

2. Methods of List Data Type in Python

Answer:

(i) Adding Values to a List

lst = [1, 2]

lst.append(3) # [1, 2, 3]

lst.insert(1, 4) # [1, 4, 2, 3]
lst.extend([5, 6]) # [1, 4, 2, 3, 5, 6]

(ii) Removing Values from a List

lst.remove(4) # [1, 2, 3, 5, 6]

lst.pop() # Removes 6 → [1, 2, 3, 5]

del lst[0] # [2, 3, 5]

(iii) Finding a Value in a List

index = lst.index(3) # Returns 1

if 5 in lst: # Checks existence

print("Found")

(iv) Sorting the Values in a List

lst.sort() # [2, 3, 5]

lst.sort(reverse=True) # [5, 3, 2]

3. Negative Indexing, Slicing & List Methods

Answer:

(a) Negative Indexing

Accesses elements from the end (-1 is last element).

lst = [10, 20, 30]

print(lst[-1]) # 30

(b) Slicing

Extracts a sublist [start:stop:step].

print(lst[1:3]) # [20, 30]

(c) index(x)

Finds the first occurrence of x.

print(lst.index(20)) # 1

(d) append(x)

Adds x to the end.

lst.append(40) # [10, 20, 30, 40]


(e) remove(x)

Removes first occurrence of x.

lst.remove(20) # [10, 30, 40]

(f) pop([i])

Removes and returns element at i.

lst.pop(1) # 30 → [10, 40]

(g) insert(i, x)

Inserts x at index i.

lst.insert(0, 5) # [5, 10, 40]

(h) sort()

Sorts the list.

lst.sort() # [5, 10, 40]

4. List Methods: len(), sum(), max(), min()

Answer:

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

print(len(lst)) # 5 (length)

print(sum(lst)) # 15 (sum)

print(max(lst)) # 5 (maximum)

print(min(lst)) # 1 (minimum)

5. Different Ways to Delete Elements from a List

Answer:

lst = [10, 20, 30, 40, 50]

# (1) del statement

del lst[1] # [10, 30, 40, 50]


# (2) remove()

lst.remove(30) # [10, 40, 50]

# (3) pop()

lst.pop() # [10, 40]

# (4) clear()

lst.clear() # []

6. copy.copy() vs copy.deepcopy()

Answer:

 copy.copy() creates a shallow copy (nested objects are referenced).

 copy.deepcopy() creates a deep copy (nested objects are also copied).

Example:

lst1 = [1, [2, 3]]

lst2 = copy.copy(lst1) # Shallow copy

lst3 = copy.deepcopy(lst1) # Deep copy

lst1[1][0] = 99

print(lst2) # [1, [99, 3]] (affected)

print(lst3) # [1, [2, 3]] (unaffected)

7. in and not in Operators in List

Answer:
Checks if an element exists in a list.

lst = [1, 2, 3]

print(2 in lst) # True

print(4 not in lst) # True


8. Dictionary vs List & Most Populous City

Answer:

 List is ordered, mutable, and allows duplicates.

 Dictionary is unordered, mutable, and stores key:value pairs.

Program:

cities = {"Mumbai": 20, "Delhi": 18, "Bangalore": 12}

max_city = max(cities, key=cities.get)

print("Most populous city:", max_city)

9. Tuple vs List & Conversion

Answer:

 Tuple is immutable (()), List is mutable ([]).

 tuple() converts a list to a tuple.

lst = [1, 2, 3]

tup = tuple(lst) # (1, 2, 3)

10. set() and setdefault() in Dictionary

Answer:

 set() creates a set (unique elements).

 setdefault(k, d) returns v for key k, else inserts k with default d.

Example:

d = {"a": 1}

print(d.setdefault("b", 2)) # 2 → d = {"a":1, "b":2}

11. Dictionary Methods

Answer:

d = {"a": 1, "b": 2}
print(d.get("a")) #1

print(d.items()) # dict_items([('a', 1), ('b', 2)])

print(d.keys()) # dict_keys(['a', 'b'])

print(d.values()) # dict_values([1, 2])

12. Different Ways to Delete from List

(Same as Q5)

13. String Slicing Outputs

Answer:

S = "Hello World"

print(S[1:5]) # 'ello'

print(S[:5]) # 'Hello'

print(S[3:-1]) # 'lo Worl'

print(S[:]) # 'Hello World'

14. Dictionary & For Loop Traversal

Answer:
A dictionary stores key:value pairs and is unordered.

Example:

d = {"a": 1, "b": 2}

for key in d:

print(key, d[key])

15. Remove Odd Numbers from List

Program:

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

lst = [x for x in lst if x % 2 == 0]


print(lst) # [2, 4]

16. List Indexing & Slicing

Answer:

a = ['hello', 'how', [1,2,3], [[10,20,30]]]

print(a[ : : ]) # ['hello', 'how', [1,2,3], [[10,20,30]]]

print(a[-3][0]) # 'how' (a[-3] = 'how' → 'h')

print(a[2][ : -1]) # [1, 2]

print(a[0][ : : -1]) # 'olleh'

17. Delete Key from Dictionary

Program:

d = {"a": 1, "b": 2}

del d["a"]

print(d) # {'b': 2}

18. Reverse Each Word in String

Program:

s = "hello how are you"

words = s.split()

reversed_words = [word[::-1] for word in words]

print(" ".join(reversed_words)) # "olleh woh era uoy"

19. Reverse Sentence in String

Program:

s = "hello how are you"

print(s[::-1]) # "uoy era woh olleh"


20. Count Even & Odd Numbers

Program:

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

even = len([x for x in lst if x % 2 == 0])

odd = len(lst) - even

print("Even:", even, "Odd:", odd)

21. Frequency of Digits

Program:

num = input("Enter a number: ")

freq = {}

for d in num:

freq[d] = freq.get(d, 0) + 1

for k, v in freq.items():

print(f"Digit {k}: {v} times")

22. Count Words, Digits, Uppercase, Lowercase

Program

s = input("Enter a sentence: ")

words = len(s.split())

digits = sum(c.isdigit() for c in s)

upper = sum(c.isupper() for c in s)

lower = sum(c.islower() for c in s)

print(f"Words: {words}, Digits: {digits}, Uppercase: {upper}, Lowercase: {lower}")

23. Mean, Variance, Standard Deviation

Program:

import statistics
data = [1, 2, 3, 4, 5]

mean = statistics.mean(data)

variance = statistics.variance(data)

stdev = statistics.stdev(data)

print(f"Mean: {mean}, Variance: {variance}, Std Dev: {stdev}")

24. Longest Word in Sentence

Program:

s = input("Enter a sentence: ")

words = s.split()

longest = max(words, key=len)

print("Longest word:", longest)

25. Blank Tic-Tac-Toe Board

Program:

def print_board():

for i in range(3):

print(" | ".join([" "]*3))

if i < 2:

print("-" * 9)

print_board()

You might also like