├── Python List Exercise.md ├── Python Loop.md └── README.md /Python List Exercise.md: -------------------------------------------------------------------------------- 1 | # Python List Exercise 2 | 3 | 1. Python program to interchange first and last elements in a list: 4 | 5 | ```python 6 | # codeswithpankaj.com 7 | def interchange_first_last(lst): 8 | lst[0], lst[-1] = lst[-1], lst[0] 9 | return lst 10 | 11 | # Example usage: 12 | my_list = [1, 2, 3, 4, 5] 13 | result_list = interchange_first_last(my_list) 14 | print(result_list) 15 | ``` 16 | 17 | 2. Python program to swap two elements in a list: 18 | 19 | ```python 20 | # codeswithpankaj.com 21 | def swap_elements(lst, pos1, pos2): 22 | lst[pos1], lst[pos2] = lst[pos2], lst[pos1] 23 | return lst 24 | 25 | # Example usage: 26 | my_list = [1, 2, 3, 4, 5] 27 | result_list = swap_elements(my_list, 1, 3) 28 | print(result_list) 29 | ``` 30 | 31 | 3. Python – Swap elements in String list: 32 | 33 | ```python 34 | # codeswithpankaj.com 35 | def swap_elements_string_list(lst, str1, str2): 36 | index1, index2 = lst.index(str1), lst.index(str2) 37 | lst[index1], lst[index2] = lst[index2], lst[index1] 38 | return lst 39 | 40 | # Example usage: 41 | my_list = ['apple', 'banana', 'cherry', 'date'] 42 | result_list = swap_elements_string_list(my_list, 'banana', 'cherry') 43 | print(result_list) 44 | ``` 45 | 46 | 4. Python | Ways to find length of list: 47 | 48 | ```python 49 | # codeswithpankaj.com 50 | def find_length_of_list(lst): 51 | length = len(lst) 52 | return length 53 | 54 | # Example usage: 55 | my_list = [1, 2, 3, 4, 5] 56 | length = find_length_of_list(my_list) 57 | print(length) 58 | ``` 59 | 60 | 5. Maximum of two numbers in Python: 61 | 62 | ```python 63 | # codeswithpankaj.com 64 | def find_maximum(a, b): 65 | return max(a, b) 66 | 67 | # Example usage: 68 | num1 = 10 69 | num2 = 20 70 | max_num = find_maximum(num1, num2) 71 | print(max_num) 72 | ``` 73 | 74 | 6. Minimum of two numbers in Python: 75 | 76 | ```python 77 | # codeswithpankaj.com 78 | def find_minimum(a, b): 79 | return min(a, b) 80 | 81 | # Example usage: 82 | num1 = 10 83 | num2 = 20 84 | min_num = find_minimum(num1, num2) 85 | print(min_num) 86 | ``` 87 | 88 | 7. Python | Ways to check if an element exists in a list: 89 | 90 | ```python 91 | # codeswithpankaj.com 92 | def check_element_exists(lst, element): 93 | return element in lst 94 | 95 | # Example usage: 96 | my_list = [1, 2, 3, 4, 5] 97 | element_to_check = 3 98 | exists = check_element_exists(my_list, element_to_check) 99 | print(exists) 100 | ``` 101 | 102 | 8. Different ways to clear a list in Python: 103 | 104 | ```python 105 | # codeswithpankaj.com 106 | def clear_list(lst): 107 | lst.clear() 108 | return lst 109 | 110 | # Example usage: 111 | my_list = [1, 2, 3, 4, 5] 112 | cleared_list = clear_list(my_list) 113 | print(cleared_list) 114 | ``` 115 | 116 | 9. Python | Reversing a List: 117 | 118 | ```python 119 | # codeswithpankaj.com 120 | def reverse_list(lst): 121 | lst.reverse() 122 | return lst 123 | 124 | # Example usage: 125 | my_list = [1, 2, 3, 4, 5] 126 | reversed_list = reverse_list(my_list) 127 | print(reversed_list) 128 | ``` 129 | 130 | 10. Python | Cloning or Copying a list: 131 | 132 | ```python 133 | # codeswithpankaj.com 134 | def clone_list(lst): 135 | cloned_list = lst.copy() 136 | return cloned_list 137 | 138 | # Example usage: 139 | my_list = [1, 2, 3, 4, 5] 140 | cloned_list = clone_list(my_list) 141 | print(cloned_list) 142 | ``` 143 | 144 | 11. Python | Count occurrences of an element in a list: 145 | 146 | ```python 147 | # codeswithpankaj.com 148 | def count_occurrences(lst, element): 149 | return lst.count(element) 150 | 151 | # Example usage: 152 | my_list = [1, 2, 3, 4, 2, 5, 2] 153 | element_to_count = 2 154 | occurrences = count_occurrences(my_list, element_to_count) 155 | print(occurrences) 156 | ``` 157 | 158 | 12. Python Program to find sum and average of List in Python: 159 | 160 | ```python 161 | # codeswithpankaj.com 162 | def calculate_sum_and_average(lst): 163 | total_sum = sum(lst) 164 | average = total_sum / len(lst) 165 | return total_sum, average 166 | 167 | # Example usage: 168 | my_list = [1, 2, 3, 4, 5] 169 | sum_result, average_result = calculate_sum_and_average(my_list) 170 | print(f"Sum: {sum_result}, Average: {average_result}") 171 | ``` 172 | 173 | 13. Python | Sum of number digits in List: 174 | 175 | ```python 176 | # codeswithpankaj.com 177 | def sum_of_digits_in_list(lst): 178 | return sum(int(digit) for number in lst for digit in str(abs(number))) 179 | 180 | # Example usage: 181 | my_list = [12, 34, 56, 78] 182 | result = sum_of_digits_in_list(my_list) 183 | print(result) 184 | ``` 185 | 186 | 14. Python | Multiply all numbers in the list: 187 | 188 | ```python 189 | # codeswithpankaj.com 190 | def multiply_numbers(lst): 191 | result = 1 192 | for number in lst: 193 | result *= number 194 | return result 195 | 196 | # Example usage: 197 | my_list = [1, 2, 3, 4, 5] 198 | product = multiply_numbers(my_list) 199 | print(product) 200 | ``` 201 | 202 | 15. Python program to find smallest number in a list: 203 | 204 | ```python 205 | # codeswithpankaj.com 206 | def find_smallest_number(lst): 207 | return min(lst) 208 | 209 | # Example usage: 210 | my_list = [5, 2, 8, 1, 6] 211 | smallest_num = find_smallest_number(my_list) 212 | print(smallest_num) 213 | ``` 214 | 215 | 16. Python program to find largest number in a list: 216 | 217 | ```python 218 | # codeswithpankaj.com 219 | def find_largest_number(lst): 220 | return max(lst) 221 | 222 | # Example usage: 223 | my_list = [5, 2, 8, 1, 6] 224 | largest_num = find_largest_number(my_list) 225 | print(largest_num) 226 | ``` 227 | 228 | 17. Python program to find second largest number in a list: 229 | 230 | ```python 231 | # codeswithpankaj.com 232 | def find_second_largest_number(lst): 233 | sorted_list = sorted(set(lst), reverse=True) 234 | return sorted_list[1] 235 | 236 | # Example usage: 237 | my_list = [5, 2, 8, 1, 6] 238 | second_largest_num = find_second_largest_number(my_list) 239 | print(second_largest_num) 240 | ``` 241 | 242 | 18. Python program to print even numbers in a list: 243 | 244 | ```python 245 | # codeswithpankaj.com 246 | def print_even_numbers(lst): 247 | even_numbers = [num for num in lst if num % 2 == 0] 248 | return even_numbers 249 | 250 | # Example usage: 251 | my_list = [1, 2, 3, 4, 5, 6] 252 | even_nums = print_even_numbers(my_list) 253 | print(even_nums) 254 | ``` 255 | 256 | 19. Python program to print odd numbers in a List: 257 | 258 | ```python 259 | # codeswithpankaj.com 260 | def print_odd_numbers(lst): 261 | odd_numbers = [num for num in lst if num % 2 != 0] 262 | return odd_numbers 263 | 264 | # Example usage: 265 | my_list = [1, 2, 3, 4, 5, 6] 266 | odd_nums = print_odd_numbers(my_list) 267 | print(odd_nums) 268 | ``` 269 | 270 | 20. Python program to print all even numbers in a range: 271 | 272 | ```python 273 | # codeswithpankaj.com 274 | def print_even_numbers_in_range(start, end): 275 | even_numbers = [num for num in range(start, end + 1) if num % 2 == 0] 276 | return even_numbers 277 | 278 | # Example usage: 279 | start_range = 1 280 | end_range = 10 281 | even_nums_range = print_even_numbers_in_range(start_range, end_range) 282 | print(even_nums_range) 283 | ``` 284 | 285 | 21. Python program to print all odd numbers in a range: 286 | 287 | ```python 288 | # codeswithpankaj.com 289 | def print_odd_numbers_in_range(start, end): 290 | odd_numbers = [num for num in range(start, end + 1) if num % 2 != 0] 291 | return odd_numbers 292 | 293 | # Example usage: 294 | start_range = 1 295 | end_range = 10 296 | odd_nums_range = print_odd_numbers_in_range(start_range, end_range) 297 | print(odd_nums_range) 298 | ``` 299 | 300 | 22. Python program to count Even and Odd numbers in a List: 301 | 302 | ```python 303 | # codeswithpankaj.com 304 | def count_even_odd_numbers(lst): 305 | even_count = sum(1 for num in lst if num % 2 == 0) 306 | odd_count = sum(1 for num in lst if num % 2 != 0) 307 | return even_count, odd_count 308 | 309 | # Example usage: 310 | my_list = [1, 2, 3, 4, 5, 6] 311 | even_count, odd_count = count_even_odd_numbers(my_list) 312 | print(f"Even Count: {even_count}, Odd Count: {odd_count}") 313 | ``` 314 | 315 | 23. Python program to print all even numbers in a range: 316 | 317 | ```python 318 | # codeswithpankaj.com 319 | def print_even_numbers_in_range(start, end): 320 | even_numbers = [num for num in range(start, end + 1) if num % 2 == 0] 321 | return even_numbers 322 | 323 | # Example usage: 324 | start_range = 1 325 | end_range = 10 326 | even_nums_range = print_even_numbers_in_range(start_range, end_range) 327 | print(even_nums_range) 328 | ``` 329 | 330 | 24. Python program to print all odd numbers in a range: 331 | 332 | ```python 333 | # codeswithpankaj.com 334 | def print_odd_numbers_in_range(start, end): 335 | odd_numbers = [num for num in range(start, end + 1) if num % 2 != 0] 336 | return odd_numbers 337 | 338 | # Example usage: 339 | start_range = 1 340 | end_range = 10 341 | odd_nums_range = print_odd_numbers_in_range(start_range, end_range) 342 | print(odd_nums_range) 343 | ``` 344 | 345 | 25. Python program to count Even and Odd numbers in a List: 346 | 347 | ```python 348 | # codeswithpankaj.com 349 | def count_even_odd_numbers(lst): 350 | even_count = sum(1 for num in lst if num % 2 == 0) 351 | odd_count = sum(1 for num in lst if num % 2 != 0) 352 | return even_count, odd_count 353 | 354 | # Example usage: 355 | my_list = [1, 2, 3, 4, 5, 6] 356 | even_count, odd_count = count_even_odd_numbers(my_list) 357 | print(f"Even Count: {even_count}, Odd Count: {odd_count}") 358 | ``` 359 | 360 | 26. Python program to print positive numbers in a list: 361 | 362 | ```python 363 | # codeswithpankaj.com 364 | def print_positive_numbers(lst): 365 | positive_numbers = [num for num in lst if num > 0] 366 | return positive_numbers 367 | 368 | # Example usage: 369 | my_list = [-1, 2, -3, 4, -5, 6] 370 | positive_nums = print_positive_numbers(my_list) 371 | print(positive_nums) 372 | ``` 373 | 374 | 27. Python program to print negative numbers in a list: 375 | 376 | ```python 377 | # codeswithpankaj.com 378 | def print_negative_numbers(lst): 379 | negative_numbers = [num for num in lst if num < 0] 380 | return negative_numbers 381 | 382 | # Example usage: 383 | my_list = [-1, 2, -3, 4, -5, 6] 384 | negative_nums = print_negative_numbers(my_list) 385 | print(negative_nums) 386 | ``` 387 | 388 | 28. Python program to print all positive numbers in a range: 389 | 390 | ```python 391 | # codeswithpankaj.com 392 | def print_positive_numbers_in_range(start, end): 393 | positive_numbers = [num for num in range(start, end + 1) if num > 0] 394 | return positive_numbers 395 | 396 | # Example usage: 397 | start_range = -5 398 | end_range = 5 399 | positive_nums_range = print_positive_numbers_in_range(start_range, end_range) 400 | print(positive_nums_range) 401 | ``` 402 | 403 | 29. Python program to print all negative numbers in a range: 404 | 405 | ```python 406 | # codeswithpankaj.com 407 | def print_negative_numbers_in_range(start, end): 408 | negative_numbers = [num for num in range(start, end + 1) if num < 0] 409 | return negative_numbers 410 | 411 | # Example usage: 412 | start_range = -5 413 | end_range = 5 414 | negative_nums_range = print_negative_numbers_in_range(start_range, end_range) 415 | print(negative_nums_range) 416 | ``` 417 | 418 | 30. Python program to count positive and negative numbers in a list: 419 | 420 | ```python 421 | # codeswithpankaj.com 422 | def count_positive_negative_numbers(lst): 423 | positive_count = sum(1 for num in lst if num > 0) 424 | negative_count = sum(1 for num in lst if num < 0) 425 | return positive_count, negative_count 426 | 427 | # Example usage: 428 | my_list = [-1, 2, -3, 4, -5, 6] 429 | positive_count, negative_count = count_positive_negative_numbers(my_list) 430 | print(f"Positive Count: {positive_count}, Negative Count: {negative_count}") 431 | ``` 432 | 433 | 31. Remove multiple elements from a list in Python: 434 | 435 | ```python 436 | # codeswithpankaj.com 437 | def remove_multiple_elements(lst, elements_to_remove): 438 | updated_list = [ele for ele in lst if ele not in elements_to_remove] 439 | return updated_list 440 | 441 | # Example usage: 442 | my_list = [1, 2, 3, 4, 5, 6] 443 | elements_to_remove = [2, 4] 444 | result_list = remove_multiple_elements(my_list, elements_to_remove) 445 | print(result_list) 446 | ``` 447 | 448 | 32. Python | Remove empty tuples from a list: 449 | 450 | ```python 451 | # codeswithpankaj.com 452 | def remove_empty_tuples(lst): 453 | updated_list = [tup for tup in lst if tup] 454 | return updated_list 455 | 456 | # Example usage: 457 | my_list = [(), (1, 2), (), (3, 4), (), (5, 6)] 458 | result_list = remove_empty_tuples(my_list) 459 | print(result_list) 460 | ``` 461 | 462 | 33. Python | Program to print duplicates from a list of integers: 463 | 464 | ```python 465 | # codeswithpankaj.com 466 | def find_duplicates(lst): 467 | seen = set() 468 | duplicates = set(num for num in lst if num in seen or seen.add(num)) 469 | return list(duplicates) 470 | 471 | # Example usage: 472 | my_list = [1, 2, 2, 3, 4, 5, 5, 6] 473 | duplicates_list = find_duplicates(my_list) 474 | print(duplicates_list) 475 | ``` 476 | 477 | 34. Remove empty List from List: 478 | 479 | ```python 480 | # codeswithpankaj.com 481 | def remove_empty_lists(lst): 482 | updated_list = [sublist for sublist in lst if sublist] 483 | return updated_list 484 | 485 | # Example usage: 486 | my_list = [[], [1, 2], [], [3, 4], [], [5, 6]] 487 | result_list = remove_empty_lists(my_list) 488 | print(result_list) 489 | ``` 490 | 491 | 35. Python – Convert List to List of dictionaries: 492 | 493 | ```python 494 | # codeswithpankaj.com 495 | def convert_list_to_dict(lst): 496 | dict_list = [{'value': item} for item in lst] 497 | return dict_list 498 | 499 | # Example usage: 500 | my_list = [1, 2, 3, 4, 5] 501 | dict_list = convert_list_to_dict(my_list) 502 | print(dict_list) 503 | ``` 504 | 505 | 36. Python – Convert Lists of List to Dictionary: 506 | 507 | ```python 508 | # codeswithpankaj.com 509 | def convert_lists_of_list_to_dict(lists_of_list): 510 | dict_list = {sublist[0]: sublist[1:] for sublist in lists_of_list} 511 | return dict_list 512 | 513 | # Example usage: 514 | my_lists_of_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 515 | dict_list = convert_lists_of_list_to_dict(my_lists_of_list) 516 | print(dict_list) 517 | ``` 518 | 519 | 37. Python | Uncommon elements in Lists of List: 520 | 521 | ```python 522 | # codeswithpankaj.com 523 | def uncommon_elements_in_lists_of_list(lists_of_list): 524 | all_elements = [item for sublist in lists_of_list for item in sublist] 525 | uncommon_elements = [ele for ele in all_elements if all_elements.count(ele) == 1] 526 | return uncommon_elements 527 | 528 | # Example usage: 529 | my_lists_of_list = [[1, 2, 3], [3, 4, 5], [5, 6, 7]] 530 | uncommon_elements = uncommon_elements_in_lists_of_list(my_lists_of_list) 531 | print(uncommon_elements) 532 | ``` 533 | 534 | 38. Python program to select Random value from list of lists: 535 | 536 | ```python 537 | import random 538 | 539 | # codeswithpankaj.com 540 | def select_random_value(list_of_lists): 541 | random_list = random.choice(list_of_lists) 542 | random_value = random.choice(random_list) 543 | return random_value 544 | 545 | # Example usage: 546 | my_list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 547 | random_value = select_random_value(my_list_of_lists) 548 | print(random_value) 549 | ``` 550 | 551 | 39. Python – Reverse Row sort in Lists of List: 552 | 553 | ```python 554 | # codeswithpankaj.com 555 | def reverse_row_sort(lists_of_list): 556 | sorted_lists = [sorted(sublist, reverse=True) for sublist in lists_of_list] 557 | return sorted_lists 558 | 559 | # Example usage: 560 | my_lists_of_list = [[3, 2, 1], [6, 5, 4], [9, 8, 7]] 561 | sorted_lists = reverse_row_sort(my_lists_of_list) 562 | print(sorted_lists) 563 | ``` 564 | 565 | 40. Python – Pair elements with Rear element in Matrix Row: 566 | 567 | ```python 568 | # codeswithpankaj.com 569 | def pair_elements_with_rear(matrix): 570 | paired_matrix = [[(matrix[row][col], matrix[row][col + 1]) for col in range(len(matrix[row]) - 1)] for row in range(len(matrix))] 571 | return paired_matrix 572 | 573 | # Example usage: 574 | my_matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 575 | paired_matrix = pair_elements_with_rear(my_matrix) 576 | print(paired_matrix) 577 | ``` 578 | 579 | 41. Python Program to count unique values inside a list: 580 | 581 | ```python 582 | # codeswithpankaj.com 583 | def count_unique_values(lst): 584 | unique_values = len(set(lst)) 585 | return unique_values 586 | 587 | # Example usage: 588 | my_list = [1, 2, 3, 1, 2, 4, 5] 589 | unique_count = count_unique_values(my_list) 590 | print(unique_count) 591 | ``` 592 | 593 | 42. Python – List product excluding duplicates: 594 | 595 | ```python 596 | # codeswithpankaj.com 597 | def product_excluding_duplicates(lst): 598 | unique_values = list(set(lst)) 599 | product_result = 1 600 | for value in unique_values: 601 | product_result *= value 602 | return product_result 603 | 604 | # Example usage: 605 | my_list = [1, 2, 3, 2, 4, 5] 606 | result = product_excluding_duplicates(my_list) 607 | print(result) 608 | ``` 609 | 610 | 43. Python – Extract elements with Frequency greater than K: 611 | 612 | ```python 613 | # codeswithpankaj.com 614 | from collections import Counter 615 | 616 | def extract_elements_with_frequency(lst, k): 617 | frequency_counter = Counter(lst) 618 | extracted_elements = [ele for ele, count in frequency_counter.items() if count > k] 619 | return extracted_elements 620 | 621 | # Example usage: 622 | my_list = [1, 2, 3, 2, 4, 5, 2] 623 | k_value = 1 624 | result = extract_elements_with_frequency(my_list, k_value) 625 | print(result) 626 | ``` 627 | 628 | 44. Python – Test if List contains elements in Range: 629 | 630 | ```python 631 | # codeswithpankaj.com 632 | def test_list_contains_elements_in_range(lst, start, end): 633 | return all(start <= ele <= end for ele in lst) 634 | 635 | # Example usage: 636 | my_list = [1, 2, 3, 4, 5] 637 | start_range = 1 638 | end_range = 5 639 | contains_elements_in_range = test_list_contains_elements_in_range(my_list, start_range, end_range) 640 | print(contains_elements_in_range) 641 | ``` 642 | 643 | 45. Python program to check if the list contains three consecutive common numbers in Python: 644 | 645 | ```python 646 | # codeswithpankaj.com 647 | def has_three_consecutive_common(lst): 648 | return any(lst[i] == lst[i+1] == lst[i+2] for i in range(len(lst)-2)) 649 | 650 | # Example usage: 651 | my_list = [1, 2, 2, 3, 3, 3, 4] 652 | has_consecutive_common = has_three_consecutive_common(my_list) 653 | print(has_consecutive_common) 654 | ``` 655 | 656 | 46. Python program to find the Strongest Neighbour: 657 | 658 | ```python 659 | # codeswithpankaj.com 660 | def find_strongest_neighbour(lst): 661 | n = len(lst) 662 | strongest_neighbours = [max(lst[i - 1], lst[i + 1]) for i in range(1, n - 1)] 663 | return strongest_neighbours 664 | 665 | # Example usage: 666 | my_list = [4, 5, 1, 2, 10] 667 | result = find_strongest_neighbour(my_list) 668 | print(result) 669 | ``` 670 | 671 | 47. Python Program to print all Possible Combinations from the three Digits: 672 | 673 | ```python 674 | # codeswithpankaj.com 675 | from itertools import permutations 676 | 677 | def print_all_combinations_three_digits(): 678 | digits = [1, 2, 3] 679 | combinations = list(permutations(digits, 3)) 680 | return combinations 681 | 682 | # Example usage: 683 | result = print_all_combinations_three_digits() 684 | print(result) 685 | ``` 686 | 687 | 48. Python program to find all the Combinations in the list with the given condition: 688 | 689 | ```python 690 | # codeswithpankaj.com 691 | from itertools import combinations 692 | 693 | def find_combinations_with_condition(lst, k): 694 | combinations_list = [comb for comb in combinations(lst, k) if sum(comb) == 10] 695 | return combinations_list 696 | 697 | # Example usage: 698 | my_list = [1, 2, 3, 4, 5] 699 | k_value = 3 700 | result = find_combinations_with_condition(my_list, k_value) 701 | print(result) 702 | ``` 703 | 704 | 49. Python program to get all unique combinations of two Lists: 705 | 706 | ```python 707 | # codeswithpankaj.com 708 | from itertools import product 709 | 710 | def get_unique_combinations_of_two_lists(list1, list2): 711 | unique_combinations = list(product(set(list1), set(list2))) 712 | return unique_combinations 713 | 714 | # Example usage: 715 | list1 = [1, 2] 716 | list2 = ['a', 'b'] 717 | result = get_unique_combinations_of_two_lists(list1, list2) 718 | print(result) 719 | ``` 720 | 721 | 50. Python program to remove all occurrences of an element from a list: 722 | 723 | ```python 724 | # codeswithpankaj.com 725 | def remove_all_occurrences(lst, element_to_remove): 726 | updated_list = [ele for ele in lst if ele != element_to_remove] 727 | return updated_list 728 | 729 | # Example usage: 730 | my_list = [1, 2, 3, 2, 4, 2, 5] 731 | element_to_remove = 2 732 | result_list = remove_all_occurrences(my_list, element_to_remove) 733 | print(result_list) 734 | ``` 735 | 736 | 51. Python – Remove Consecutive K element records: 737 | 738 | ```python 739 | # codeswithpankaj.com 740 | def remove_consecutive_k_element_records(lst, k): 741 | updated_list = [ele for ele, count in zip(lst, lst[1:] + [None]) if count != k] 742 | return updated_list 743 | 744 | # Example usage: 745 | my_list = [1, 1, 2, 2, 2, 3, 4, 4, 5] 746 | k_value = 2 747 | result_list = remove_consecutive_k_element_records(my_list, k_value) 748 | print(result_list) 749 | ``` 750 | 751 | 52. Python – Replace index elements with elements in Other List: 752 | 753 | ```python 754 | # codeswithpankaj.com 755 | def replace_index_elements_with_other_list(lst1, lst2): 756 | for index, ele in enumerate(lst2): 757 | if index < len(lst1): 758 | lst1[index] = ele 759 | return lst1 760 | 761 | # Example usage: 762 | list1 = [1, 2, 3, 4, 5] 763 | list2 = ['a', 'b', 'c'] 764 | result_list = replace_index_elements_with_other_list(list1, list2) 765 | print(result_list) 766 | ``` 767 | 768 | 53. Python Program to Retain records with N occurrences of K: 769 | 770 | ```python 771 | # codeswithpankaj.com 772 | from collections import Counter 773 | 774 | def retain_records_with_n_occurrences(lst, k, n): 775 | frequency_counter = Counter(lst) 776 | retained_records = [ele for ele in lst if frequency_counter[ele] == n] 777 | return retained_records 778 | 779 | # Example usage: 780 | my_list = [1, 2, 3, 1, 2, 4, 5, 2] 781 | element_to_retain = 2 782 | occurrences_to_retain = 2 783 | result = retain_records_with_n_occurrences(my_list, element_to_retain, occurrences_to_retain) 784 | print(result) 785 | ``` 786 | 787 | 54. Python Program to Sort the list according to the column using lambda: 788 | 789 | ```python 790 | # codeswithpankaj.com 791 | def sort_list_by_column(lst, column): 792 | sorted_list = sorted(lst, key=lambda x: x[column]) 793 | return sorted_list 794 | 795 | # Example usage: 796 | my_list = [(1, 4), (2, 3), (3, 2), (4, 1)] 797 | column_to_sort = 1 798 | result_list = sort_list_by_column(my_list, column_to_sort) 799 | print(result_list) 800 | ``` 801 | 802 | 803 | 804 | -------------------------------------------------------------------------------- /Python Loop.md: -------------------------------------------------------------------------------- 1 | # Question 2 | 3 | 4 | 1. Print the first 10 natural numbers using for loop. 5 | 2. Python program to print all the even numbers within the given range. 6 | 3. Python program to calculate the sum of all numbers from 1 to a given number. 7 | 4. Python program to calculate the sum of all the odd numbers within the given range. 8 | 5. Python program to print a multiplication table of a given number 9 | 6. Python program to display numbers from a list using a for loop. 10 | 7. Python program to count the total number of digits in a number. 11 | 8. Python program to check if the given string is a palindrome. 12 | 9. Python program that accepts a word from the user and reverses it. 13 | 10. Python program to check if a given number is an Armstrong number 14 | 11. Python program to count the number of even and odd numbers from a series of numbers. 15 | 12. Python program to display all numbers within a range except the prime numbers. 16 | 13. Python program to get the Fibonacci series between 0 to 50. 17 | 14. Python program to find the factorial of a given number. 18 | 15. Python program that accepts a string and calculates the number of digits and letters. 19 | 16. Write a Python program that iterates the integers from 1 to 25. 20 | 17. Python program to check the validity of password input by users. 21 | 18. Python program to convert the month name to a number of days. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python interview questions along with their answers : 2 | 3 | 1. **What is Python?** 4 | - *Answer:* Python is a high-level, interpreted programming language known for its simplicity and readability. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming. 5 | 6 | 2. **Explain the difference between Python 2 and Python 3.** 7 | - *Answer:* Python 2 and Python 3 are two major versions of the language. Python 3 is the latest and has backward-incompatible changes. Some key differences include print statement (Python 2) vs. print() function (Python 3), Unicode handling, and division. 8 | 9 | 3. **What is PEP 8?** 10 | - *Answer:* PEP 8 (Python Enhancement Proposal 8) is the style guide for Python code. It provides guidelines on how to format code for better readability and consistency. 11 | 12 | 4. **What is the purpose of the `__init__` method in Python?** 13 | - *Answer:* The `__init__` method is a special method in Python classes that is called when an object is created. It is used to initialize the object's attributes. 14 | 15 | 5. **Explain the concept of list comprehension.** 16 | - *Answer:* List comprehension is a concise way to create lists in Python. It allows you to create a new list by specifying the expression to be evaluated for each item in an existing iterable (e.g., list, tuple) along with optional conditions. 17 | 18 | 6. **What is the Global Interpreter Lock (GIL) in Python?** 19 | - *Answer:* The Global Interpreter Lock (GIL) is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecode at once. This can impact the performance of multi-threaded Python programs. 20 | 21 | 7. **Explain the differences between a shallow copy and a deep copy.** 22 | - *Answer:* A shallow copy creates a new object, but does not create copies of nested objects; it only copies references. A deep copy, on the other hand, creates a new object and recursively creates copies of all nested objects. 23 | 24 | 8. **What is the purpose of the `__str__` method?** 25 | - *Answer:* The `__str__` method is used to define the "informal" or user-friendly string representation of an object. It is called when the `str()` function is invoked on an object. 26 | 27 | 9. **How does exception handling work in Python?** 28 | - *Answer:* Python uses a try-except block for exception handling. Code within the try block is executed, and if an exception occurs, the corresponding except block is executed. This helps in handling errors gracefully. 29 | 30 | 10. **Explain the use of the `with` statement in Python.** 31 | - *Answer:* The `with` statement is used for resource management, specifically for dealing with files, sockets, or any object that supports the context management protocol. It ensures proper acquisition and release of resources. 32 | 33 | 11. **What is a decorator in Python?** 34 | - *Answer:* A decorator is a design pattern in Python that allows the modification of functions or methods using the `@decorator` syntax. It is often used for aspects like logging, authentication, or modifying behavior without changing the original code. 35 | 36 | 12. **Explain the use of the `yield` keyword in Python.** 37 | - *Answer:* The `yield` keyword is used in the context of a generator function to produce a sequence of values iteratively. It allows the function to pause its execution and retain its state, making it memory-efficient for large data sets. 38 | 39 | 13. **What is the difference between a tuple and a list in Python?** 40 | - *Answer:* A tuple is immutable (unchangeable), while a list is mutable. Tuples are defined using parentheses `()` and lists using square brackets `[]`. Tuples are generally used for heterogeneous data, and lists for homogeneous data. 41 | 42 | 14. **What is the purpose of the `__name__` variable in Python?** 43 | - *Answer:* The `__name__` variable is a special variable that is set to `"__main__"` when the Python script is executed directly. It is often used to determine whether the script is the main program or being imported as a module. 44 | 45 | 15. **Explain the use of the `super()` function in Python.** 46 | - *Answer:* The `super()` function is used to call a method from a parent class in an inheritance hierarchy. It is commonly used in the `__init__` method of a subclass to invoke the constructor of the parent class. 47 | 48 | 16. **What is the purpose of the `*args` and `**kwargs` in function definitions?** 49 | - *Answer:* `*args` and `**kwargs` allow a function to accept a variable number of arguments. `*args` collects positional arguments into a tuple, and `**kwargs` collects keyword arguments into a dictionary. 50 | 51 | 17. **Explain the Global Interpreter Lock (GIL) and its impact on multi-threading.** 52 | - *Answer:* The Global Interpreter Lock (GIL) in CPython prevents multiple native threads from executing Python bytecode in parallel. This can impact the performance of multi-threaded programs as only one thread can execute Python bytecode at a time. 53 | 54 | 18. **What is the difference between shallow copy and deep copy in Python? Provide examples.** 55 | - *Answer:* Shallow copy creates a new object but does not create copies of nested objects. Deep copy creates a new object and recursively copies all nested objects. Example: 56 | ```python 57 | import copy 58 | 59 | original_list = [1, [2, 3], 4] 60 | shallow_copy = copy.copy(original_list) 61 | deep_copy = copy.deepcopy(original_list) 62 | ``` 63 | 64 | 19. **Explain the purpose of the `__call__` method in Python.** 65 | - *Answer:* The `__call__` method allows an object to be called as a function. It is executed when the instance is called using the function call syntax. This is useful for creating callable objects. 66 | 67 | 20. **How does Python's garbage collection work?** 68 | - *Answer:* Python uses automatic memory management with a garbage collector. The `gc` module provides an interface for garbage collection. The most common form of garbage collection is reference counting, but cyclic garbage collection is also used to detect and collect circular references. 69 | 70 | 21. **What is a lambda function in Python?** 71 | - *Answer:* A lambda function is an anonymous function defined using the `lambda` keyword. It is often used for short, simple operations and can take multiple arguments but can only have one expression. 72 | 73 | 22. **Explain the purpose of the `__init__` and `__new__` methods in Python classes.** 74 | - *Answer:* The `__init__` method is called after the object has been created to initialize its attributes. The `__new__` method is responsible for creating a new instance of the class and is called before `__init__`. 75 | 76 | 23. **How can you handle exceptions in Python? Provide examples of try-except blocks.** 77 | - *Answer:* Exceptions in Python can be handled using try-except blocks. Example: 78 | ```python 79 | try: 80 | result = 10 / 0 81 | except ZeroDivisionError as e: 82 | print(f"Error: {e}") 83 | ``` 84 | 85 | 24. **What is the purpose of the `__slots__` attribute in a Python class?** 86 | - *Answer:* The `__slots__` attribute is used to explicitly declare data members in a class. It restricts the creation of new attributes at runtime, potentially saving memory and improving performance. 87 | 88 | 25. **Explain the differences between a set and a frozenset in Python.** 89 | - *Answer:* A set is mutable and unordered, while a frozenset is immutable and hashable. Sets are defined using curly braces `{}`, and frozensets using the `frozenset()` constructor. 90 | 91 | 26. **How does Python's `zip()` function work?** 92 | - *Answer:* The `zip()` function combines multiple iterables element-wise and returns an iterator of tuples. It stops when the shortest input iterable is exhausted. Example: 93 | ```python 94 | names = ["Alice", "Bob", "Charlie"] 95 | ages = [25, 30, 22] 96 | zipped = zip(names, ages) 97 | ``` 98 | 99 | 27. **Explain the use of the `__getitem__` and `__setitem__` methods in Python.** 100 | - *Answer:* The `__getitem__` method allows accessing an item using square bracket notation, and `__setitem__` allows modifying an item. These methods are part of the Python data model and are used in classes that want to emulate sequence behavior. 101 | 102 | 28. **What is the Global Interpreter Lock (GIL) and how does it affect multiprocessing in Python?** 103 | - *Answer:* The GIL is a mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecode at once. In multiprocessing, each process has its own Python interpreter and memory space, so the GIL does not affect parallel execution. 104 | 105 | 29. **Explain the purpose of the `enumerate()` function in Python.** 106 | - *Answer:* The `enumerate()` function is used to iterate over a sequence while keeping track of the index and the corresponding value. It returns tuples containing the index and the value. Example: 107 | ```python 108 | for index, value in enumerate(["apple", "banana", "cherry"]): 109 | print(index, value) 110 | ``` 111 | 112 | 30. **How does Python handle default arguments in function definitions?** 113 | - *Answer:* Default arguments are specified in the function definition and have a default value. If a value is not provided for a default argument, the default value is used. Example: 114 | ```python 115 | def greet(name, greeting="Hello"): 116 | print(f"{greeting}, {name}!") 117 | ``` 118 | 119 | 31. **Explain the purpose of the `__str__` and `__repr__` methods in Python.** 120 | - *Answer:* The `__str__` method is used to define the "informal" or user-friendly string representation of an object, while `__repr__` is used for the "formal" or developer-oriented representation. `__repr__` is more for debugging. 121 | 122 | 32. **What is the purpose of the `*` operator in function arguments?** 123 | - *Answer:* The `*` operator is used for unpacking iterables in function arguments. It allows passing a variable number of positional arguments to a function. Example: 124 | ```python 125 | def sum_values(*args): 126 | return sum(args) 127 | ``` 128 | 129 | 33. **Explain the concept of a generator in Python.** 130 | - *Answer:* A generator is a special type of iterator in Python. It is created using a function with the `yield` keyword, allowing the function to retain its state and produce a sequence of values lazily, improving memory efficiency. 131 | 132 | 34. **What is the purpose of the `__doc__` attribute in Python?** 133 | - *Answer:* The `__doc__` attribute is used to access the docstring (documentation string) of a Python object, such as a module, class, or function. It provides information about the object's purpose and usage. 134 | 135 | 35. **Explain the concept of a context manager in Python.** 136 | - *Answer:* A context manager in Python is an object that defines the methods `__enter__` and `__exit__`. It is used with the `with` statement to manage resources, such as opening and closing files or acquiring and releasing locks. 137 | 138 | 36. **How does the `filter()` function work in Python?** 139 | - *Answer:* The `filter()` function is used to construct an iterator from elements of an iterable for which a function returns true. It takes a function and an iterable and returns an iterator containing only the elements that satisfy the given function. Example: 140 | ```python 141 | numbers = [1, 2, 3, 4, 5] 142 | filtered_numbers = filter(lambda x: x % 2 == 0, numbers) 143 | ``` 144 | 145 | 37. **What is the purpose of the `async` and `await` keywords in Python?** 146 | - *Answer:* The `async` and `await` keywords are used in asynchronous programming to define asynchronous functions and to wait for the completion of asynchronous tasks, respectively. They are part of the `asyncio` module. 147 | 148 | 38. **Explain the purpose of the `collections` module in Python.** 149 | - *Answer:* The `collections` module provides specialized data structures not available in the built-in types. For example, `Counter` for counting occurrences in a collection, `namedtuple` for creating named tuples, and `deque` for double-ended queues. 150 | 151 | 39. **How does the `any()` and `all()` functions work in Python?** 152 | - *Answer:* The `any()` function returns `True` if at least one element in an iterable is true. The `all()` function returns `True` if all elements in an iterable are true. Example: 153 | ```python 154 | values = [True, False, True] 155 | any_result = any(values) 156 | all_result = all(values) 157 | ``` 158 | 159 | 40. **Explain the purpose of the `itertools` module in Python.** 160 | - *Answer:* The `itertools` module provides a collection of fast, memory-efficient tools for working with iterators. It includes functions like `cycle` (endlessly iterates over an iterable), `chain` (concatenates multiple iterables), and `count` (generates an infinite sequence of numbers). 161 | 162 | 41. **What is the Global Interpreter Lock (GIL), and how does it impact multithreading in Python?** 163 | - *Answer:* The Global Interpreter Lock (GIL) is a mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecode at once. This can impact the performance of multithreaded Python programs, as only one thread can execute Python bytecode at a time. 164 | 165 | 42. **Explain the purpose of the `staticmethod` and `classmethod` decorators in Python.** 166 | - *Answer:* The `staticmethod` decorator is used to define a static method within a class that does not access or modify class or instance state. The `classmethod` decorator is used to define a method that takes the class itself as its first argument, rather than an instance. 167 | 168 | 43. **How does garbage collection work in Python, and what is the purpose of the `gc` module?** 169 | - *Answer:* Python uses automatic memory management with a garbage collector. The `gc` module provides an interface for garbage collection, allowing manual control over the garbage collector and providing functions for debugging memory management. 170 | 171 | 44. **Explain the purpose of the `__next__` method and the `StopIteration` exception in Python iterators.** 172 | - *Answer:* The `__next__` method is used to retrieve the next item from an iterator. When there are no more items, it should raise the `StopIteration` exception to signal the end of the iteration. In Python 3, the `StopIteration` exception is automatically handled in loops. 173 | 174 | 45. **What are metaclasses in Python?** 175 | - *Answer:* Metaclasses are a way to customize class creation in Python. They define how new classes are created and can be thought of as "class of a class." Metaclasses are used less frequently but can be powerful for advanced customization and code generation. 176 | 177 | 46. **Explain the purpose of the `functools` module in Python.** 178 | - *Answer:* The `functools` module provides higher-order functions and operations on callable objects. It includes functions like `partial` (creates partially applied functions), `reduce` (applies a binary function successively), and `wraps` (creates well-behaved decorators). 179 | 180 | 47. **How do you handle file I/O in Python? Provide examples of reading and writing to a file.** 181 | - *Answer:* File I/O in Python is typically handled using the `open()` function. Example of reading from a file: 182 | ```python 183 | with open('example.txt', 'r') as file: 184 | content = file.read() 185 | ``` 186 | Example of writing to a file: 187 | ```python 188 | with open('output.txt', 'w') as file: 189 | file.write('Hello, World!') 190 | ``` 191 | 192 | 48. **Explain the purpose of the `__enter__` and `__exit__` methods in a context manager.** 193 | - *Answer:* The `__enter__` method is called when entering a `with` block and is responsible for acquiring the necessary resources. The `__exit__` method is called when exiting the block and is responsible for releasing resources. Context managers are often used with the `with` statement. 194 | 195 | 49. **What is the purpose of the `os` module in Python?** 196 | - *Answer:* The `os` module in Python provides a way of interacting with the operating system. It includes functions for file and directory manipulation, process management, environment variables, and more. 197 | 198 | 50. **Explain the differences between shallow copy and deep copy in Python. Provide examples.** 199 | - *Answer:* Shallow copy creates a new object but does not create copies of nested objects. Deep copy creates a new object and recursively copies all nested objects. Example: 200 | ```python 201 | import copy 202 | 203 | original_list = [1, [2, 3], 4] 204 | shallow_copy = copy.copy(original_list) 205 | deep_copy = copy.deepcopy(original_list) 206 | ``` 207 | 208 | 51. **Explain the purpose of the `zip()` function in Python, and provide an example.** 209 | - *Answer:* The `zip()` function in Python combines multiple iterables element-wise and returns an iterator of tuples. Example: 210 | ```python 211 | names = ["Alice", "Bob", "Charlie"] 212 | ages = [25, 30, 22] 213 | zipped = zip(names, ages) 214 | ``` 215 | 216 | 52. **What is a Python decorator, and how is it used? Provide an example.** 217 | - *Answer:* A decorator is a design pattern in Python that allows the modification of functions or methods using the `@decorator` syntax. Example: 218 | ```python 219 | def my_decorator(func): 220 | def wrapper(): 221 | print("Something is happening before the function is called.") 222 | func() 223 | print("Something is happening after the function is called.") 224 | return wrapper 225 | 226 | @my_decorator 227 | def say_hello(): 228 | print("Hello!") 229 | 230 | say_hello() 231 | ``` 232 | 233 | 53. **Explain the purpose of the `map()` function in Python, and provide an example.** 234 | - *Answer:* The `map()` function applies a given function to all items in an input iterable and returns an iterator of the results. Example: 235 | ```python 236 | numbers = [1, 2, 3, 4, 5] 237 | squared = map(lambda x: x**2, numbers) 238 | ``` 239 | 240 | 54. **What is the purpose of the `__slots__` attribute in a Python class?** 241 | - *Answer:* The `__slots__` attribute is used to explicitly declare data members in a class. It restricts the creation of new attributes at runtime, potentially saving memory and improving performance. 242 | 243 | 55. **Explain the purpose of the `sys` module in Python.** 244 | - *Answer:* The `sys` module provides access to some variables used or maintained by the Python interpreter, such as command line arguments, the Python path, and the standard input/output streams. 245 | 246 | 56. **How can you create a virtual environment in Python?** 247 | - *Answer:* You can create a virtual environment using the `venv` module. Example: 248 | ``` 249 | python -m venv myenv 250 | ``` 251 | 252 | 57. **Explain the purpose of the `requests` library in Python.** 253 | - *Answer:* The `requests` library is used for making HTTP requests in Python. It provides a simple API for sending HTTP/1.1 requests and handling responses. 254 | 255 | 58. **What is the purpose of the `logging` module in Python?** 256 | - *Answer:* The `logging` module provides flexible logging of messages in Python applications. It allows developers to configure different log handlers, set log levels, and route log messages to various destinations. 257 | 258 | 59. **Explain the use of the `filter()` function in Python. Provide an example.** 259 | - *Answer:* The `filter()` function constructs an iterator from elements of an iterable for which a function returns true. Example: 260 | ```python 261 | numbers = [1, 2, 3, 4, 5] 262 | even_numbers = filter(lambda x: x % 2 == 0, numbers) 263 | ``` 264 | 265 | 60. **How can you handle exceptions in Python? Provide examples of try-except blocks.** 266 | - *Answer:* Exceptions in Python can be handled using try-except blocks. Example: 267 | ```python 268 | try: 269 | result = 10 / 0 270 | except ZeroDivisionError as e: 271 | print(f"Error: {e}") 272 | ``` 273 | 274 | 61. **Explain the purpose of the `sorted()` function in Python, and how does it differ from the `sort()` method?** 275 | - *Answer:* The `sorted()` function returns a new sorted list from the elements of any iterable, while the `sort()` method is an in-place operation that sorts a list. Example: 276 | ```python 277 | numbers = [3, 1, 4, 1, 5, 9, 2] 278 | sorted_numbers = sorted(numbers) 279 | ``` 280 | 281 | 62. **What is the purpose of the `__str__` and `__repr__` methods in Python?** 282 | - *Answer:* The `__str__` method is used to define the "informal" or user-friendly string representation of an object, while `__repr__` is used for the "formal" or developer-oriented representation. `__repr__` is more for debugging. 283 | 284 | 63. **Explain the purpose of the `*args` and `**kwargs` in function definitions.** 285 | - *Answer:* `*args` and `**kwargs` allow a function to accept a variable number of arguments. `*args` collects positional arguments into a tuple, and `**kwargs` collects keyword arguments into a dictionary. 286 | 287 | 64. **What is the purpose of the `itertools` module in Python?** 288 | - *Answer:* The `itertools` module provides a collection of fast, memory-efficient tools for working with iterators. It includes functions like `cycle` (endlessly iterates over an iterable), `chain` (concatenates multiple iterables), and `count` (generates an infinite sequence of numbers). 289 | 290 | 65. **Explain the purpose of the `json` module in Python.** 291 | - *Answer:* The `json` module in Python is used for encoding and decoding JSON data. It provides functions like `json.dumps()` to serialize Python objects into a JSON-formatted string and `json.loads()` to deserialize a JSON-formatted string into Python objects. 292 | 293 | 66. **How can you handle file I/O in Python? Provide examples of reading and writing to a file.** 294 | - *Answer:* File I/O in Python is typically handled using the `open()` function. Example of reading from a file: 295 | ```python 296 | with open('example.txt', 'r') as file: 297 | content = file.read() 298 | ``` 299 | Example of writing to a file: 300 | ```python 301 | with open('output.txt', 'w') as file: 302 | file.write('Hello, World!') 303 | ``` 304 | 305 | 67. **Explain the purpose of the `collections` module in Python.** 306 | - *Answer:* The `collections` module provides specialized data structures not available in the built-in types. For example, `Counter` for counting occurrences in a collection, `namedtuple` for creating named tuples, and `deque` for double-ended queues. 307 | 308 | 68. **What is the purpose of the `__init__` method in Python classes?** 309 | - *Answer:* The `__init__` method is a special method in Python classes that is called when an object is created. It is used to initialize the object's attributes. 310 | 311 | 69. **Explain the use of the `with` statement in Python.** 312 | - *Answer:* The `with` statement is used for resource management, specifically for dealing with files, sockets, or any object that supports the context management protocol. It ensures proper acquisition and release of resources. 313 | 314 | 70. **How does Python's garbage collection work?** 315 | - *Answer:* Python uses automatic memory management with a garbage collector. The `gc` module provides an interface for garbage collection. The most common form of garbage collection is reference counting, but cyclic garbage collection is also used to detect and collect circular references. 316 | 317 | 71. **Explain the purpose of the `enumerate()` function in Python.** 318 | - *Answer:* The `enumerate()` function is used to iterate over a sequence (such as a list) while keeping track of the index and the corresponding value. It returns tuples containing the index and the value. Example: 319 | ```python 320 | for index, value in enumerate(["apple", "banana", "cherry"]): 321 | print(index, value) 322 | ``` 323 | 324 | 72. **What is a Python decorator, and how is it used? Provide an example.** 325 | - *Answer:* A decorator is a design pattern in Python that allows the modification of functions or methods using the `@decorator` syntax. Example: 326 | ```python 327 | def my_decorator(func): 328 | def wrapper(): 329 | print("Something is happening before the function is called.") 330 | func() 331 | print("Something is happening after the function is called.") 332 | return wrapper 333 | 334 | @my_decorator 335 | def say_hello(): 336 | print("Hello!") 337 | 338 | say_hello() 339 | ``` 340 | 341 | 73. **Explain the purpose of the `__slots__` attribute in a Python class.** 342 | - *Answer:* The `__slots__` attribute is used to explicitly declare data members in a class. It restricts the creation of new attributes at runtime, potentially saving memory and improving performance. 343 | 344 | 74. **What is the purpose of the `filter()` function in Python? Provide an example.** 345 | - *Answer:* The `filter()` function constructs an iterator from elements of an iterable for which a function returns true. Example: 346 | ```python 347 | numbers = [1, 2, 3, 4, 5] 348 | even_numbers = filter(lambda x: x % 2 == 0, numbers) 349 | ``` 350 | 351 | 75. **Explain the concept of a context manager in Python.** 352 | - *Answer:* A context manager in Python is an object that defines the methods `__enter__` and `__exit__`. It is used with the `with` statement to manage resources, such as opening and closing files or acquiring and releasing locks. 353 | 354 | 76. **What is the purpose of the `sys.argv` list in Python?** 355 | - *Answer:* The `sys.argv` list in Python contains command-line arguments passed to a script. `sys.argv[0]` is the script name, and subsequent elements contain the arguments. 356 | 357 | 77. **Explain the purpose of the `super()` function in Python.** 358 | - *Answer:* The `super()` function is used to call a method from a parent class in an inheritance hierarchy. It is commonly used in the `__init__` method of a subclass to invoke the constructor of the parent class. 359 | 360 | 78. **How does Python handle default arguments in function definitions?** 361 | - *Answer:* Default arguments are specified in the function definition and have a default value. If a value is not provided for a default argument, the default value is used. Example: 362 | ```python 363 | def greet(name, greeting="Hello"): 364 | print(f"{greeting}, {name}!") 365 | ``` 366 | 367 | 79. **Explain the purpose of the `async` and `await` keywords in Python.** 368 | - *Answer:* The `async` and `await` keywords are used in asynchronous programming to define asynchronous functions and to wait for the completion of asynchronous tasks, respectively. They are part of the `asyncio` module. 369 | 370 | 80. **What is the purpose of the `shutil` module in Python?** 371 | - *Answer:* The `shutil` module provides a higher-level interface for file operations. It includes functions for file copying, moving, and archiving, as well as utility functions for working with file paths. 372 | 373 | 81. **Explain the purpose of the `collections.Counter` class in Python.** 374 | - *Answer:* The `Counter` class in the `collections` module is used to count the occurrences of elements in a collection (e.g., list, tuple, or string). It returns a dictionary-like object where keys are elements, and values are their counts. 375 | 376 | 82. **What is the purpose of the `contextlib` module in Python?** 377 | - *Answer:* The `contextlib` module provides utilities for working with context managers. It includes the `contextmanager` decorator for creating context managers using generators. 378 | 379 | 83. **Explain the Global Interpreter Lock (GIL) and its impact on CPU-bound and I/O-bound tasks.** 380 | - *Answer:* The GIL is a mutex that protects access to Python objects and prevents multiple native threads from executing Python bytecode at once. It primarily impacts CPU-bound tasks negatively but has a lesser impact on I/O-bound tasks as threads can release the GIL during I/O operations. 381 | 382 | 84. **What is the purpose of the `__call__` method in Python?** 383 | - *Answer:* The `__call__` method allows an object to be called as a function. It is executed when the instance is called using the function call syntax. This is useful for creating callable objects. 384 | 385 | 85. **How can you handle multiple exceptions in a single `except` block in Python?** 386 | - *Answer:* Multiple exceptions can be handled in a single `except` block by specifying them as a tuple. Example: 387 | ```python 388 | try: 389 | # code that may raise exceptions 390 | except (TypeError, ValueError) as e: 391 | # handle both TypeError and ValueError 392 | ``` 393 | 394 | 86. **Explain the purpose of the `threading` module in Python.** 395 | - *Answer:* The `threading` module provides a way to create and manage threads in Python. It includes functions for thread creation, synchronization, and communication. 396 | 397 | 87. **What is the purpose of the `__name__` variable in Python scripts?** 398 | - *Answer:* The `__name__` variable is a special variable that is set to `"__main__"` when the Python script is executed directly. It is often used to determine whether the script is the main program or being imported as a module. 399 | 400 | 88. **Explain the purpose of the `random` module in Python.** 401 | - *Answer:* The `random` module provides functions for generating pseudorandom numbers. It includes functions for random selection, shuffling, and generating random integers and floats. 402 | 403 | 89. **What is the purpose of the `functools.partial` function in Python?** 404 | - *Answer:* The `functools.partial` function is used for partial function application. It allows fixing a certain number of arguments of a function and generating a new function with the remaining arguments as parameters. 405 | 406 | 90. **Explain the purpose of the `repr()` function in Python.** 407 | - *Answer:* The `repr()` function is used to obtain the formal string representation of an object. It is often used for debugging and development, providing a representation that, if passed to `eval()`, would recreate the object. 408 | 409 | 91. **Explain the purpose of the `__doc__` attribute in Python.** 410 | - *Answer:* The `__doc__` attribute is used to access the docstring (documentation string) of a Python object, such as a module, class, or function. It provides information about the object's purpose and usage. 411 | 412 | 92. **What is the purpose of the `*` operator in unpacking iterables?** 413 | - *Answer:* The `*` operator is used for unpacking iterables in function arguments and assignments. It allows passing a variable number of elements as arguments or creating new iterables by combining existing ones. 414 | 415 | 93. **Explain the purpose of the `functools.wraps` decorator in Python.** 416 | - *Answer:* The `functools.wraps` decorator is used to update a wrapper function to look more like the wrapped function. It copies attributes such as `__name__` and `__doc__` to the wrapper, making it behave more like the original function. 417 | 418 | 94. **How does the `any()` and `all()` functions work in Python?** 419 | - *Answer:* The `any()` function returns `True` if at least one element in an iterable is true. The `all()` function returns `True` if all elements in an iterable are true. Example: 420 | ```python 421 | values = [True, False, True] 422 | any_result = any(values) 423 | all_result = all(values) 424 | ``` 425 | 426 | 95. **Explain the purpose of the `try`...`except`...`else` block in Python.** 427 | - *Answer:* The `try`...`except`...`else` block is used to handle exceptions in Python. Code inside the `try` block is executed, and if an exception occurs, the `except` block is executed. If no exception occurs, the `else` block is executed. 428 | 429 | 96. **What is the purpose of the `is` operator in Python?** 430 | - *Answer:* The `is` operator is used to test object identity. It returns `True` if two variables reference the same object, and `False` otherwise. 431 | 432 | 97. **Explain the purpose of the `os.path` module in Python.** 433 | - *Answer:* The `os.path` module provides a platform-independent way of using operating system-dependent functionality related to file paths. It includes functions for path manipulation, such as joining paths and retrieving directory names and file names. 434 | 435 | 98. **How can you handle keyboard interrupts (`Ctrl+C`) in a Python script?** 436 | - *Answer:* Keyboard interrupts can be handled using a `try`...`except` block with the `KeyboardInterrupt` exception. For example: 437 | ```python 438 | try: 439 | # code that may be interrupted 440 | while True: 441 | pass 442 | except KeyboardInterrupt: 443 | print("Interrupted by user!") 444 | ``` 445 | 446 | 99. **What is the purpose of the `timeit` module in Python?** 447 | - *Answer:* The `timeit` module is used for measuring the execution time of small code snippets. It provides a simple interface to measure the execution time of Python statements or functions. 448 | 449 | 100. **Explain the purpose of the `zip()` function in Python, and how can it be used to unzip a list of tuples?** 450 | - *Answer:* The `zip()` function combines multiple iterables element-wise and returns an iterator of tuples. To unzip a list of tuples, you can use the `zip(*iterable)` syntax. Example: 451 | ```python 452 | names = ["Alice", "Bob", "Charlie"] 453 | ages = [25, 30, 22] 454 | zipped = zip(names, ages) 455 | 456 | # Unzip 457 | unzipped_names, unzipped_ages = zip(*zipped) 458 | ``` 459 | 460 | --------------------------------------------------------------------------------