1. Lists
- What are Lists?
- Lists Vs Arrays
- Characterstics of a List
- How to create a list
- Access items from a List
- Editing items in a List
- Deleting items from a List
- Operations on Lists
- Functions on Lists
What are Lists
List is a data type where you can store multiple items under 1 name. More technically, lists act like dynamic arrays which means you can add more items on the fly.
- Why Lists are required in programming?
Array Vs Lists
- Fixed Vs Dynamic Size
- Convenience -> Hetrogeneous
- Speed of Execution
- Memory
Example 1
Explanation
- Code imports unused modules and functions that aren't actually used in the following lines
- Prints memory addresses (id values) of a list and its individual elements
- Shows that list elements share the same memory address as their corresponding integer values
- Demonstrates Python's object identity and memory management concepts
- Output shows identical id values for the same integer objects (1, 2, 3) across different locations in memory
Output
Characterstics of a List
- Ordered
- Changeble/Mutable
- Hetrogeneous
- Can have duplicates
- are dynamic
- can be nested
- items can be accessed
- can contain any kind of objects in python
Example 2
Explanation
- Compares two lists L and L1 for equality using the == operator
- Checks if both lists have the same elements in the same order
- Uses Python's built-in comparison functionality for sequences
- Returns False because although both lists contain the same numbers, their order is different
- The comparison evaluates element by element from left to right, finding mismatch at index 0
Output
Creating a List
Example 3
Explanation
- Prints empty list followed by various nested list structures showing different dimensions and data types
- Demonstrates homogeneous lists (same data types) vs heterogeneous lists (mixed data types)
- Shows 1D list with integers, 2D list with mixed nested structure, 3D list with triple nesting
- Uses type conversion with
list()function to convert string 'Hello' into list of characters - Outputs each list structure to show how Python handles different dimensional arrays and mixed data types
Output
Accessing items from a List
Example 4
Explanation
- Accesses elements in lists using positive and negative indices, printing values at specific positions
- Uses nested list indexing to access elements within nested lists, including deep nesting levels
- Demonstrates slice notation with
[::-1]to reverse the entire list structure - Shows how negative indexing works from the end of lists, accessing last elements with -1, -2, etc.
- Prints nested list structures and their individual components, revealing the hierarchical nature of multi-dimensional lists
Output
Example 5
Explanation
- Code demonstrates Python list slicing with various index patterns and step values
- Uses standard slice notation
[start:end:step]with positive and negative indices - Prints sublists by extracting elements from original list L using different slicing ranges
- Shows negative indexing where -1 refers to last element, -2 to second last, etc.
- Output shows how slicing creates new lists without modifying original list L
Output
Adding Items to a List
Example 6
Explanation
- Creates a list L with initial values [1,2,3,4,5] and then appends the integer 6 and boolean True to the end of the list
- Uses the append() method which adds a single element to the end of a list
- The list now contains [1, 2, 3, 4, 5, 6, True] with the boolean value True being added as a separate element
- Prints the updated list showing all elements including the newly appended items
- The append() method modifies the original list in-place rather than creating a new list
Output
Example 7
Explanation
- Creates a list L with initial values [1,2,3,4,5]
- Uses the extend() method to add multiple elements [6,7,8] to the end of the list
- The extend() function takes an iterable and appends each element individually to the list
- Prints the modified list showing all elements: [1, 2, 3, 4, 5, 6, 7, 8]
- Unlike append(), extend() adds individual elements rather than the entire iterable as a single element
Output
Example 8
Explanation
- The code creates a list L with elements 1, 2, 3, 4, 5
- It uses the append() method to add the entire list [6,7,8] as a single element to the end of L
- The append() function adds its argument as one complete item rather than individual elements
- The print statement outputs the modified list showing the nested structure
- Expected output is [1, 2, 3, 4, 5, [6, 7, 8]] with the new elements grouped together in a sub-list
Output
Example 9
Explanation
- The code creates a list L with integers 1,2,3,4,5 and then extends it with the string 'delhi'
- The extend() method adds each character of the string 'delhi' as individual elements to the list
- Key function used is extend() which modifies the original list by adding iterable elements
- Expected output is [1, 2, 3, 4, 5, 'd', 'e', 'l', 'h', 'i'] - the original integers followed by individual characters
- Side effect is that the original list L is permanently modified in place
Output
Example 10
Explanation
- The code creates a list L with integers 1, 2, 3, 4, 5
- The extend() method adds each character from the string 'd' as individual elements to the list
- Since strings are iterable, 'd' gets added as a single character element rather than the entire string
- The print statement outputs the modified list showing all original integers plus the new character element
- Key function used is extend() which modifies the list in-place by adding iterable elements
Output
Example 11
Explanation
- The code attempts to extend a list L with the integer 6, but this will cause a TypeError because extend() expects an iterable, not a single element
- Key function used is extend() which adds multiple elements from an iterable to the end of a list
- The code will raise a TypeError: 'int' object is not iterable when trying to execute L.extend(6)
- If the code worked as intended, it would add the number 6 as a separate element to the list
- Expected behavior would be to use L.append(6) instead to add a single element to the list
Output
Example 12
Explanation
- The code creates a list L with integers 1 through 5, then extends it with the boolean value True
- In Python, when you extend a list with a boolean, True is treated as 1 and False as 0
- The extend() method adds each element of the iterable to the end of the list
- Since True equals 1 numerically, the list gets the value 1 appended to it
- The output will be [1, 2, 3, 4, 5, 1] because True is converted to 1 and added to the end
Output
Example 13
Explanation
- Inserts the value 100 at index position 1 in the list L
- The insert() method shifts existing elements at and after index 1 to the right
- Original list [1,2,3,4,5] becomes [1,100,2,3,4,5] after insertion
- Key function used is list.insert(index, value) which modifies the list in-place
- Output will be the modified list: [1, 100, 2, 3, 4, 5]
Output
Example 14
Explanation
- Inserts the string 'delhi' at index position 1 in the list L
- The insert() method shifts all existing elements at or after index 1 one position to the right
- Original list [1,2,3,4,5] becomes [1,'delhi',2,3,4,5] after insertion
- Key function used is list.insert(index, element) which modifies the list in-place
- Output prints the modified list: [1, 'delhi', 2, 3, 4, 5]
Output
Editing Items in a List
Example 15
Explanation
- Initializes a list
Lwith integers from 1 to 5. - Modifies the last element of the list (index -1) to be 500.
- Uses the
print()function to output the modified list. - Expected output is
[1, 2, 3, 4, 500], showing the change made to the last element.
Output
Example 16
Explanation
- The code initializes a list
Lcontaining the integers 1 through 5. - It replaces the elements from index 2 to 4 (inclusive of 2, exclusive of 5) with the new list
[300, 400, 500]. - The slice assignment modifies the original list
Ldirectly. - The
printfunction outputs the modified list. - The expected output is
[1, 2, 300, 400, 500].
Output
Deleting Items from a List
Example 17
Explanation
- Initializes a list
Lcontaining integers from 1 to 5. - Prints the list
L, displaying[1, 2, 3, 4, 5]. - Uses the
delstatement to delete the listL, removing it from memory. - Attempts to print
Lagain, which will raise aNameErrorsinceLno longer exists.
Output
Example 18
Explanation
- Initializes a list
Lcontaining the integers 1 through 5. - Prints the original list
L, which outputs:[1, 2, 3, 4, 5]. - Uses the
delstatement to remove the element at index 2 (the value 3) from the list. - Prints the modified list
L, which now outputs:[1, 2, 4, 5].
Output
Example 19
Explanation
- Initializes a list
Lcontaining the integers 1 through 5. - Prints the original list
L, which outputs[1, 2, 3, 4, 5]. - Uses the
delstatement to remove the elements at index 2 and 3 (values 3 and 4) from the list. - Prints the modified list
L, which outputs[1, 2, 5].
Output
Example 20
Explanation
- Initializes a list
Lcontaining five integers: 100, 200, 300, 400, and 500. - Uses the
remove()method to delete the first occurrence of the value300from the listL. - The
print()function outputs the modified list after the removal operation. - The expected output will be:
[100, 200, 400, 500], showing that300has been removed.
Output
Example 21
Explanation
- Initializes a list
Lcontaining the integers 1 through 5. - Uses the
pop()method to remove and return the element at index 0 (the first element) of the list. - The
print()function outputs the modified list after the pop operation. - The expected output is
[2, 3, 4, 5], as the first element (1) has been removed.
Output
Example 22
Explanation
- Initializes a list
Lcontaining the integers 1 through 5. - Uses the
pop()method to remove and return the last element of the list (which is 5). - The
print(L)statement outputs the modified list, which now contains[1, 2, 3, 4].
Output
Example 23
Explanation
- Initializes a list
Lcontaining the integers 1 through 5. - Calls the
clear()method on the listL, which removes all elements from the list. - Prints the modified list
L, which is now empty. - The expected output is
[], indicating that the list has been cleared.
Output
Operations on Lists
- Arithmetic
- Membership
- Loop
Example 24
Explanation
- The code defines two lists,
L1andL2, containing integers. - It uses the
+operator to concatenate the two lists, merging their elements into a single list. - The
printfunction outputs the result of the concatenation to the console. - The expected output is the combined list:
[1, 2, 3, 4, 5, 6, 7, 8].
Output
Example 25
Explanation
- Multiplies the list
L1by 3, which repeats the elements of the list three times. - The
print()function outputs the result to the console. - If
L1is[1, 2], the output will be[1, 2, 1, 2, 1, 2].
Output
Example 26
Explanation
- Multiplies two lists,
L1andL2, element-wise if they are of the same length. - Uses the
print()function to output the result to the console. - If
L1andL2are not of the same length, it will raise aTypeError. - The expected output is a new list containing the products of corresponding elements from
L1andL2.
Output
Example 27
Explanation
- Checks if elements exist within lists using the
inandnot inoperators - Uses the
print()function to display boolean results of membership tests - Tests membership of integer 5 in L1 (True) and L2 (False since 5 is not directly in L2)
- Tests membership of list [5,6] in L2 (True) since the nested list exists as an element
- Shows that
inoperator looks for exact matches at the immediate level of nesting
Output
Example 28
Explanation
- Code iterates through two different lists using for loops to print each element
- First loop processes L1 which contains integers 1 through 5, printing them one by one
- Second loop processes L2 which contains mixed data types including a nested list [5,6]
- The print function displays each item in the lists during iteration
- Output shows individual elements from L1 on separate lines, then all elements of L2 including the nested list as a single item
Output
List Functions
Example 29
Explanation
- Prints the length of list L which is 5
- Finds and prints the minimum value in list L which is 0
- Finds and prints the maximum value in list L which is 7
- Creates and prints a new sorted version of list L in ascending order [0,1,2,5,7]
- Creates and prints a new sorted version of list L in descending order [7,5,2,1,0]
- Calculates and prints the sum of all elements in list L which is 15
Output
Example 30
Explanation
- The code creates a list L with integers 1,2,1,3,4,1,5 and counts occurrences of specific values
- Uses the list method
.count()to count how many times a value appears in the list - First prints 3 because the number 1 appears 3 times in the list
- Second prints 0 because the number 100 doesn't appear in the list at all
- The
.count()method returns an integer representing the frequency of the specified element
Output
Example 31
Explanation
- The code creates a list L with repeated elements including multiple occurrences of the number 1
- It uses the
.index()method to find the position of specific values in the list L.index(5)returns 6 because 5 is at index 6 (0-based counting)L.index(1)returns 0 because it finds the first occurrence of 1 at index 0- The
.index()method stops at the first match and doesn't continue searching for other occurrences
Output
Example 32
Explanation
- The code creates a list L with elements [2,1,5,7,0] and then calls the reverse() method on it
- The reverse() method permanently modifies the original list by reversing the order of its elements in-place
- After calling L.reverse(), the list becomes [0,7,5,1,2] with elements in reverse order
- The print() function displays the permanently modified list to the console
- This is a destructive operation that changes the original list object rather than creating a new reversed list
Output
Example 33
Explanation
- The code demonstrates the difference between
sorted()and.sort()methods for arranging list elements sorted(L)returns a new sorted list without modifying the original list, whileL.sort()sorts the original list in-place- The
sorted()function creates and returns a new list with elements arranged in ascending order - The
.sort()method modifies the original list object directly, changing its order permanently - Output shows original list [2,1,5,7,0], then sorted copy [0,1,2,5,7], original unchanged, then final sorted original [0,1,2,5,7]
Output
Example 34
Explanation
- Creates a list L with values [2,1,5,7,0] and prints its contents and memory address
- Uses the copy() method to create a new shallow copy of L called L1, which has the same elements but different memory address
- Assigns L to L2 using direct reference, so L2 points to the exact same memory location as L
- Prints the contents and memory addresses of all three variables to show that L1 has a different address while L and L2 share the same address
- Demonstrates the difference between shallow copying (copy()) and reference assignment (L2 = L) in Python
Output
List Comprehension
List Comprehension provides a concise way of creating lists.
newlist = [expression for item in iterable if condition == True]
Advantages of List Comprehension
- More time-efficient and space-efficient than loops.
- Require fewer lines of code.
- Transforms iterative statement into a formula.
Example 35
Explanation
- Creates an empty list and fills it with numbers 1 through 10 using a for loop
- Uses
range(1,11)to generate numbers from 1 to 10 (inclusive) andappend()to add each number to the list - The
print()function displays the final list containing all numbers from 1 to 10 - Key APIs used:
range(),list.append(), andprint() - Output will be
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Output
Example 36
Explanation
- Creates a list containing numbers from 1 to 10 using list comprehension
- Uses
range(1,11)to generate numbers starting at 1 up to (but not including) 11 - The list comprehension
[i for i in range(1,11)]iterates through each number and adds it to the list - Prints the final list
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]to the console - No side effects beyond creating the list and printing it
Output
Example 37
Explanation
- This code performs scalar multiplication by multiplying each element of vector
vby scalars - It uses a for loop to iterate through each element in the list
vand multiplies it by-3 - The
append()method adds each multiplied result to the new listx - Key operations include list iteration, arithmetic multiplication, and list building
- Expected output is
[-6, -9, -12]where each original vector element is scaled by -3
Output
Example 38
Explanation
- Multiplies each element of vector v by scalar s using list comprehension
- Key operation is the expression
[s*i for i in v]which scales every vector component - Uses Python's list comprehension syntax for concise element-wise multiplication
- Vector v = [2,3,4] gets scaled by -3 to produce [-6, -9, -12]
- No variables are modified in-place, instead a new list is created with scaled values
Output
Example 39
Explanation
- Creates a new list containing the square of each number in the original list L
- Uses list comprehension syntax
[expression for item in iterable]to efficiently transform data - The expression
i*icalculates the square of each element i from list L - Results in a new list [1, 4, 9, 16, 25] without modifying the original list
- This is a concise way to apply a mathematical operation to all elements in a collection
Output
Example 40
Explanation
- Creates a list comprehension that generates numbers from 1 to 50
- Filters numbers using the condition
i%5 == 0to keep only those divisible by 5 - Uses the modulo operator
%to check divisibility - Produces a list of all multiples of 5 between 1 and 50
- Output will be
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
Output
Example 41
Explanation
- Creates a list of programming languages and filters them based on whether they start with the letter 'p'.
- Uses a list comprehension to iterate over the
languageslist. - The
startswithmethod checks if each language begins with 'p'. - The output will be a new list containing 'python' and 'php'.
Output
Example 42
Explanation
- Creates a list comprehension to filter fruits from
my_fruitsbased on two conditions. - Checks if each fruit in
my_fruitsexists in thebasketlist. - Additionally checks if the fruit starts with the letter 'a'.
- The resulting list will contain fruits that meet both conditions.
- Expected output is
['apple'], as it is the only fruit that exists in both lists and starts with 'a'.
Output
Example 43
Explanation
- Creates a 3x3 matrix using nested list comprehensions.
- The outer list comprehension iterates over
jfrom 1 to 3, while the inner one iterates overifrom 1 to 3. - Each element of the matrix is the product of
iandj. - The resulting matrix is
[[1, 2, 3], [2, 4, 6], [3, 6, 9]]. - The code does not print the matrix; to display it, a print statement would be needed.
Output
Example 44
Explanation
- Creates a list comprehension that generates all possible products between elements of two lists
- Uses nested loops in the comprehension where each element from L1 is multiplied by each element from L2
- Key API is list comprehension syntax with multiple for clauses for nested iteration
- Produces a flat list of 16 products: [5, 6, 7, 8, 10, 12, 14, 16, 15, 18, 21, 24, 20, 24, 28, 32]
- This implements a Cartesian product operation by combining every element from first list with every element from second list
Output
2 ways to traverse a list
- itemwise
- indexwise
Example 45
Explanation
- Code iterates through each element in list L and prints every individual item
- Uses a for loop to go through the list sequentially from first to last element
- Prints each number on a separate line: 1, then 2, then 3, then 4
- The variable i takes on the value of each list element during each loop iteration
- Output shows each list item displayed one per line in order
Output
Example 46
Explanation
- Iterates through list L using index positions from 0 to length of list minus 1
- Prints each index position followed by a dash and the corresponding list element
- Uses range() function to generate sequential index numbers
- Accesses list elements using bracket notation with index variable i
- Output shows index numbers 0, 1, 2, 3 paired with values 1, 2, 3, 4 respectively
Output
Zip
The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together.
If the passed iterators have different lengths, the iterator with the least items decides the length of the new iterator.
Example 47
Explanation
- Combines two lists element-wise using zip() to pair up corresponding elements from each list
- Uses list comprehension with zip() to add corresponding elements together creating a new list with summed values
- The zip() function pairs up elements at the same positions from both input lists
- Creates a new list where each element is the sum of elements at the same index from the original two lists
- Output will be [6, 8, 10, 12] which represents 1+5, 2+6, 3+7, and 4+8 respectively
Output
Example 48
Explanation
- Code iterates through a list of lists, unpacking each inner list into variables i and j
- Uses nested iteration to process pairs of numbers from the outer list
- Calls print() function to display the sum of each pair on separate lines
- Key APIs/functions: for loop with tuple unpacking, print() function
- Expected output shows 3 and 7 printed on separate lines (1+2=3, 3+4=7)
Output
Example 49
Explanation
- Creates a list L containing four elements: the integers 1 and 2, the print function, the type function, and the input function
- The list includes both data values (1, 2) and callable functions (print, type, input)
- When printed, the list shows all four elements including the function objects in their default representation
- The print function is stored as a callable object within the list structure
- The input function is also stored as a callable object within the list structure
Output
Disadvantages of Python Lists
- Slow
- Risky usage
- eats up more memory
Example 50
Explanation
- Creates list
awith values [1,2,3] and assignsbto reference the same list object - Both
aandbpoint to the same memory location since lists are mutable objects in Python - When
a.append(4)is called, bothaandbshow the updated value [1,2,3,4] because they reference the same object - Prints the list contents twice before and after appending to demonstrate that changes affect both variables
- Shows that mutable objects like lists share references when assigned to multiple variables, causing side effects when modified
Output
Example 51
Explanation
- Creates a list
awith values [1,2,3] and makes a shallow copy of it intobusing the.copy()method - Prints both lists initially, showing they contain the same values [1,2,3]
- Appends the value 4 to list
a, modifying it to become [1,2,3,4] - Prints both lists again, showing that
anow contains [1,2,3,4] whilebstill contains [1,2,3] because.copy()created an independent list - Demonstrates that
.copy()creates a new list object rather than just copying the reference to the same list
Output
###Problem 1: Combine two lists index-wise(columns wise)
Write a program to add two lists index-wise. Create a new list that contains the 0th index item from both the list, then the 1st index item, and so on till the last element. any leftover items will get added at the end of the new list.
Given List:
Output:
Example 52
Explanation
- Combines two lists element-wise using zip function to create pairs of corresponding elements
- Uses list comprehension to transform the zipped pairs into nested lists format
- zip() function pairs up elements from both lists based on their positions
- First print statement outputs list of tuples like [('M', 'y'), ('na', 'me'), ('i', 's'), ('Kh', 'an')]
- Second print statement outputs list of lists like [['M', 'y'], ['na', 'me'], ['i', 's'], ['Kh', 'an']]
Output
Problem 2: Add new item to list after a specified item
Write a program to add item 7000 after 6000 in the following Python List
Output:
Example 53
Explanation
- The code creates a nested list structure with multiple levels of nesting
- It accesses the element at index 2 of list1, then index 2 of that nested list, then appends the value 7000 to it
- The append() method modifies the original nested list in-place without creating a new list
- The expected output shows the modified nested structure with 7000 added to the deepest nested list
- This demonstrates how to access and modify elements in deeply nested Python lists using multiple index references
Output
###Problem 3: Update no of items available
Suppose you are given a list of candy and another list of same size representing no of items of respective candy.
i.e -
Write a program to show no. of items of each candy type.
Output:
Example 54
Explanation
- Creates two lists containing candy names and their quantities, then zips them together to pair each candy with its count
- Uses the zip() function to combine the two lists element-wise into tuples, then converts the result to a list for printing
- Prints each candy name and quantity on separate lines using a list comprehension with print() and tuple unpacking
- The first print statement outputs a list of tuples showing candy names paired with their quantities
- The second print statement displays each candy and its count separated by a dash on individual lines
Output
###Problem 4: Running Sum on list
Write a program to print a list after performing running sum on it.
i.e:
Input:
Output:
Example 55
Explanation
- The code calculates a running sum (also called cumulative sum) of all numbers in list1
- It uses a for loop to iterate through each element in the list and adds it to a running total
- The
append()method adds each new running sum to the result list - Key functions used:
forloop,append(), and basic arithmetic addition - Expected output is [1, 3, 6, 10, 15, 21] - each number represents the sum of all previous numbers plus current one
Output
###Problem 5: You are given a list of integers. You are asked to make a list by running through elements of the list by adding all elements greater and itself.
i.e. Say given list is [2,4,6,10,1]
resultant list will be [22,20,10,23].
For 1st element 2 ->> these are greater (4+6+10) values and 2 itself so on adding becomes 22.
For 2nd element 4 ->> greater elements are (6, 10) and 4 itself, so on adding 20
like wise for all other elememts.
[2,4,6,10,1]-->[22,20,16,10,23]
Example 56
Explanation
- Code iterates through each element in list L and calculates sum of all elements greater than or equal to current element
- Uses nested loops where outer loop picks each element as reference point (i) and inner loop compares it with all elements (j)
- For each reference element, it accumulates sum of all elements that are greater than or equal to it
- Appends calculated sum to result list for each iteration of outer loop
- Output will be [22, 20, 18, 16, 1] where each value represents sum of elements >= corresponding element in original list
Output
###Problem 6: Find list of common unique items from two list. and show in increasing order
Input
Output:
Example 57
Explanation
- Initializes two lists,
num1andnum2, containing integers. - Creates an empty list
resultto store common elements found in bothnum1andnum2. - Iterates through each element in
num1, checking if it exists innum2; if it does, the element is added toresult. - Sorts the
resultlist in ascending order. - Prints the sorted list of common elements between
num1andnum2.
Output
###Problem 7: Sort a list of alphanumeric strings based on product value of numeric character in it. If in any string there is no numeric character take it's product value as 1.
Input:
Output:
Example 58
Explanation
- The code processes a list of strings to calculate the product of all digits in each string
- It uses nested loops to iterate through each character in strings and multiplies digit characters together
- The
isdigit()method identifies numeric characters, andint()converts them for multiplication - Results are stored as pairs of (product, original_string) and sorted in descending order by product value
- The final output shows the original strings sorted by their digit products from highest to lowest
Output
Problem 8: Split String of list on K character.
Example :
Input:
Output:
Example 59
Explanation
- The code takes a list of strings and splits each string by spaces, then combines all words into a single list
- It uses
split()method to break each string into words based on space delimiter - The
extend()method adds individual words from each split operation to the result list - Key functions used:
split(),extend(), andprint() - Expected output:
['CampusX', 'is', 'a', 'channel', 'for', 'data-science', 'aspirants.']
Output
Problem 9: Convert Character Matrix to single String using string comprehension.
Example 1:
Input:
Output:
Example 60
Explanation
- The code creates a list of lists containing individual characters
- It uses list comprehension with
"".join()to convert each inner list into a string by joining its characters - The first print statement outputs a list of strings:
['campux', 'is', 'best', 'channel'] - The second print statement joins all the resulting strings with spaces between them:
campux is best channel - The
join()method is used twice - once to build individual words and once to combine words with spaces
Output
Problem 10: Add Space between Potential Words.
Example:
Input:
Output:
Example 61
Explanation
- The code processes a list of strings to split them at uppercase letters and reassemble with spaces between words
- It uses
isupper()to detect uppercase characters as word boundaries,append()to build sublists, andjoin()to combine characters into strings - For each string, it creates temporary sublists for each word segment, then joins these segments with spaces
- The
tempvariable builds nested lists where each inner list contains consecutive lowercase characters or a single uppercase character - Output shows intermediate steps for each string and final result list containing space-separated words like
['campusx Is', 'best For', 'data Scientist']
Output
Problem 11: Write a program that can perform union operation on 2 lists
Example:
Input:
Output:
Example 62
Explanation
- The code creates a union of two lists by combining all unique elements from both lists while avoiding duplicates
- It uses basic loop structures and the
not inoperator to check for existing elements before appending to the result list - The
append()method adds elements to the end of the union list when they haven't been added already - The algorithm processes L1 first, then L2, ensuring each element appears only once in the final union list
- Expected output is [1, 2, 3, 4, 5, 7, 8] - all unique values from both input lists in order of first appearance
Output
Problem 12: Write a program that can find the max number of each row of a matrix
Example:
Input:
Output:
Example 63
Explanation
- Code iterates through each sublist in the 2D list L and finds the maximum value in each sublist
- Uses the built-in max() function to identify largest number in each inner list
- Appends each maximum value to a new result list
- Prints the final result list containing [3, 6, 9] as output
- Side effect is storing the maximum values from each row in the new result list
Output
Problem 13: Write a list comprehension to print the following matrix
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
Example 64
Explanation
- Creates a nested list comprehension that generates a 3x3 matrix
- For each row
ifrom 0 to 2, creates a row with three elements calculated asj + 3*iwherejranges from 0 to 2 - Uses list comprehension syntax to build both outer and inner lists in one expression
- Each element follows the pattern: row index multiplied by 3, plus column index position
- Produces a matrix where values increase diagonally from top-left to bottom-right
Output
Problem 14: Write a list comprehension that can transpose a given matrix
matrix = [ [1,2,3], [4,5,6], [7,8,9]]
[1, 4, 7] [2, 5, 8] [3, 6, 9]
Example 65
Explanation
- This code transposes a 3x3 matrix by swapping rows with columns using nested list comprehensions
- The outer comprehension iterates through column indices (0 to 2) using
range(len(matrix)) - The inner comprehension collects elements from each row at the current column index
iusingrow[i] - Key APIs used include list comprehension syntax,
len()function, and indexing operations - Expected output is a new transposed matrix:
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]where original rows become columns
Output
Problem 15: Write a list comprehension that can flatten a nested list
Input matrix = [ [1,2,3], [4,5,6], [7,8,9]]
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Example 66
Explanation
- Code prints all elements from a 2D matrix in row-major order, displaying numbers 1 through 9 separated by spaces
- Uses nested for loops to iterate through each row and then each item within that row
- Employs list comprehension syntax to flatten the 2D matrix into a 1D list containing all items
- The print statement shows side effect of displaying output to console
- Returns flattened list [1, 2, 3, 4, 5, 6, 7, 8, 9] as result of list comprehension expression
Output

