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
Understanding Python object identity and memory addresses through list element analysis
Explanation
- The code demonstrates how Python assigns unique memory addresses to objects using the id() function, showing that each list element and literal value has its own memory location
- It reveals that list elements share the same memory address as their corresponding literal values (L[0] and 1, L[1] and 2, L[2] and 3), indicating Python's object reuse optimization
- The output illustrates Python's memory management strategy where identical immutable objects like integers are stored only once in memory and referenced by multiple variables
- This behavior showcases fundamental concepts of Python's object model including object identity, reference counting, and memory efficiency optimizations
- The debug imports suggest this code might be part of a deeper investigation into Python's internal object handling mechanisms
Output
Characteristics 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
Comparing two lists for equality in Python programming
Explanation
- The code creates two lists L and L1 with identical elements but in different orders
- The comparison operator == checks if the two lists have the same elements in the exact same sequence
- Since list order matters in Python, L == L1 evaluates to False even though both lists contain the same values
- This demonstrates that Python's equality operator performs ordered comparison between sequences
- The result highlights the importance of element positioning when comparing list structures
Output
Creating a List
Python list creation and nesting demonstration with homogeneous and heterogeneous data types
Explanation
- Empty lists are created using square brackets with no elements, demonstrating the basic syntax for initializing empty collections
- Lists can contain mixed data types including integers, floats, strings, booleans, and complex numbers, showcasing their heterogeneous nature
- Nested lists can be created by embedding one list inside another, enabling multi-dimensional data structures like 2D and 3D arrays
- The list() constructor can convert iterable objects such as strings into lists, where each character becomes an individual element
- Homogeneous lists contain elements of the same type while heterogeneous lists mix different data types within the same structure
Output
Accessing items from a List
Understanding Python List Indexing with Positive and Negative Indices
Explanation
- The code demonstrates how to access elements in a list using both positive and negative indexing.
- Positive indexing starts from 0, allowing access to elements directly, while negative indexing starts from -1, accessing elements from the end of the list.
- The snippet includes nested lists, showcasing how to access elements within sublists using multiple indexing levels.
- The use of slicing with
L[::-1]reverses the list, illustrating another way to manipulate list order. - Each print statement outputs specific elements from the lists, helping to visualize the indexing process.
Output
Understanding list slicing techniques in Python for efficient data manipulation
Explanation
- The code demonstrates various ways to slice a list
L, which contains integers from 1 to 6. L[0:3]retrieves the first three elements of the list, resulting in[1, 2, 3].L[-3:-1]extracts elements from the third last to the second last, yielding[4, 5].L[-3:]returns all elements from the third last to the end of the list, producing[4, 5, 6].L[0::2]selects every second element starting from the first, resulting in[1, 3, 5].L[::-2]reverses the list and selects every second element, giving[6, 4, 2].L[-5:-2:2]retrieves elements from the fifth last to the second last with a step of 2, resulting in[2, 4].
Output
Adding Items to a List
This code demonstrates how to add elements to a list in Python.
Explanation
- A list
Lis initialized with five integer elements: 1, 2, 3, 4, and 5. - The
appendmethod is used to add the integer6to the end of the list. - The
appendmethod is then used again to add the boolean valueTrueto the list. - Finally, the updated list
Lis printed, displaying all its elements including the newly added ones.
Output
This code snippet demonstrates how to extend a list in Python by adding multiple elements at once.
Explanation
- The list
Lis initialized with five integer elements: 1, 2, 3, 4, and 5. - The
extend()method is called on the listL, which adds the elements 6, 7, and 8 to the end of the list. - The
print()function outputs the updated list, which now contains all eight integers: 1 through 8. - This method is useful for efficiently appending multiple items to a list in a single operation.
Output
This code demonstrates how to append a list to another list in Python.
Explanation
- A list
Lis initialized with five integer elements: 1, 2, 3, 4, and 5. - The
append()method is used to add a new list[6, 7, 8]as a single element to the end of listL. - The
print()function outputs the modified list, which now contains six elements, with the last element being the entire appended list. - The resulting structure of
Lwill be[1, 2, 3, 4, 5, [6, 7, 8]], showcasing that the appended list is nested within the original list.
Output
This code demonstrates how to extend a list with characters from a string in Python.
Explanation
- The list
Lis initialized with five integer elements: 1, 2, 3, 4, and 5. - The
extendmethod is called on the listLwith the string 'delhi', which adds each character of the string as separate elements to the list. - After the extension, the list
Lwill contain both the original integers and the individual characters from the string. - The
printfunction outputs the modified list, showing the result of the extension operation.
Output
Python list extend method adds individual characters from a string to a numeric list
Explanation
- The code initializes a list L with integer values [1, 2, 3, 4, 5]
- The extend() method is called with the string 'd' as argument, which adds each character of the string as separate elements to the list
- Since strings are iterable in Python, the extend() method iterates through each character in 'd' and appends them individually
- The print statement outputs the modified list containing both original integers and the character 'd'
- This demonstrates how extend() treats strings as iterables and adds each element separately rather than adding the entire string as one element
Output
Understanding the TypeError when extending a list with an integer in Python
Explanation
- The code attempts to extend a list with an integer value 6, which causes a TypeError because extend() expects an iterable object
- Lists in Python can only be extended with iterables such as other lists, tuples, or strings, not single values
- When you call L.extend(6), Python tries to iterate over the integer 6, which is not iterable, resulting in a runtime error
- To properly add a single element to a list, you should use append() instead of extend()
- The correct approach would be to use L.append(6) to add the integer 6 as a single element to the list
Output
Python list extend method behavior with boolean values
Explanation
- The code initializes a list L with integer values [1,2,3,4,5]
- When extend() is called with True as argument, Python treats the boolean value as an integer (True equals 1)
- The extend() method adds each element from the iterable to the list, so True gets converted to 1 and added to the list
- The final list becomes [1,2,3,4,5,1] because extend adds elements individually rather than the entire object
- This demonstrates Python's implicit type conversion where boolean values are treated as integers in list operations
Output
This code demonstrates how to insert an element into a specific position in a Python list.
Explanation
- A list
Lis initialized with five integer elements:[1, 2, 3, 4, 5]. - The
insertmethod is called on the listLto add the integer100at index1, shifting subsequent elements to the right. - The modified list is then printed, resulting in the output:
[1, 100, 2, 3, 4, 5]. - This method allows for dynamic modification of lists without overwriting existing elements.
Output
This code snippet demonstrates how to insert an element into a specific position in a Python list.
Explanation
- A list
Lis initialized with five integer elements:[1, 2, 3, 4, 5]. - The
insertmethod is called on the listLto add the string'delhi'at index1, shifting subsequent elements to the right. - The modified list is then printed, resulting in the output:
[1, 'delhi', 2, 3, 4, 5]. - This showcases the ability to dynamically modify lists in Python by inserting elements at desired positions.
Output
Editing Items in a List
This code modifies the last element of a list and prints the updated list.
Explanation
- A list
Lis initialized with five integer elements: 1, 2, 3, 4, and 5. - The last element of the list is accessed using the negative index
-1, which refers to the last item. - The last element is then updated to the value
500. - Finally, the modified list is printed, displaying the change made to the last element.
Output
This code snippet demonstrates how to modify a portion of a list in Python using slicing.
Explanation
- A list
Lis initialized with five integer elements:[1, 2, 3, 4, 5]. - The slice
L[2:5]targets the elements at indices 2, 3, and 4 (values 3, 4, and 5) for replacement. - The slice is replaced with a new list
[300, 400, 500], effectively changing the original list. - The
print(L)statement outputs the modified list, which will be[1, 2, 300, 400, 500].
Output
Deleting Items from a List
Example 17
Explanation
- The code creates a list
Lwith values [1,2,3,4,5] and prints it - The
delstatement is used to delete the entire list variableLfrom memory - After deletion, attempting to print
Lraises aNameErrorbecause the variable no longer exists - This demonstrates how
delremoves variables entirely rather than just clearing their contents - Expected output shows the list printed once, then crashes with NameError on second print attempt
Output
This code demonstrates how to remove an element from a list in Python using the del statement.
Explanation
- A list
Lis initialized with five integer elements:[1, 2, 3, 4, 5]. - The original list is printed to the console.
- The
delstatement is used to remove the element at index2, which corresponds to the value3. - The modified list is printed, showing the updated contents:
[1, 2, 4, 5].
Output
Example 19
Explanation
- The code demonstrates the
delstatement in Python, which removes elements from a list by index - It first creates a list
Lwith values [1,2,3,4,5] and prints it - The
del L[2:4]command removes elements from index 2 up to (but not including) index 4 - This removes the elements at indices 2 and 3, which are the values 3 and 4
- The final output shows the list [1, 2, 5] after the deletion operation
Output
Example 20
Explanation
- This code removes the element with value 300 from the list L using the remove() method
- The remove() function searches for the first occurrence of the specified value and deletes it from the list
- After removal, the remaining elements shift their indices to fill the gap
- The expected output is [100, 200, 400, 500] - the list with the middle element removed
- This operation modifies the original list in-place rather than creating a new list
Output
This code demonstrates how to remove an element from a list using the pop method in Python.
Explanation
- The list
Lis initialized with five integer elements:[1, 2, 3, 4, 5]. - The
pop(0)method is called on the list, which removes the element at index 0 (the first element, which is1). - After the pop operation, the list
Lis modified to[2, 3, 4, 5]. - The
print(L)statement outputs the updated list to the console. - The
popmethod can also be used to remove elements from other indices by providing a different index as an argument.
Output
This code snippet demonstrates how to remove the last element from a list in Python using the pop method.
Explanation
- The list
Lis initialized with five integer elements: 1, 2, 3, 4, and 5. - The
pop()method is called on the listL, which removes the last element (5) from the list. - After the pop operation, the modified list is printed, showing the remaining elements: [1, 2, 3, 4].
- The
pop()method also returns the removed element, but it is not captured in this snippet.
Output
This code snippet demonstrates how to clear a list in Python using the clear() method.
Explanation
- The list
Lis initialized with five integer elements: 1, 2, 3, 4, and 5. - The
clear()method is called on the listL, which removes all elements from the list, resulting in an empty list. - The
print(L)statement outputs the current state of the list, which will be[], indicating that the list has been cleared.
Output
Operations on Lists
- Arithmetic
- Membership
- Loop
Merging two lists in Python using concatenation
Explanation
- The code defines two lists, L1 and L2, containing integer elements.
- It uses the
+operator to concatenate the two lists, resulting in a single list that combines elements from both. - The
printfunction outputs the merged list to the console, displaying the combined elements in order.
Output
This code snippet demonstrates how to repeat a list multiple times in Python.
Explanation
- The code uses the
printfunction to output the result of the operation. L1is expected to be a list defined earlier in the code.- The
*operator is used to repeat the listL1three times. - The output will be a new list containing the elements of
L1concatenated three times. - If
L1is empty, the output will also be an empty list.
Output
This code snippet multiplies two lists element-wise in Python.
Explanation
- The code attempts to multiply two lists, L1 and L2, using the
*operator. - In Python, using
*between two lists will raise a TypeError, as lists cannot be directly multiplied. - To achieve element-wise multiplication, one would typically use a library like NumPy or a list comprehension.
- If L1 and L2 are intended to be numeric values, they should be defined as such before multiplication.
- The code serves as a reminder that list operations in Python require specific methods or libraries for mathematical operations.
Output
Example 27
Explanation
- The code creates two lists L1 and L2 with nested structure, then tests membership and non-membership operations using
inandnot inoperators - Key APIs used:
inoperator to check if elements exist in lists,not inoperator to check if elements don't exist in lists - The
inoperator returns True if the exact element is found at any level of nesting, False otherwise - Expected output shows that 5 is in L1 (True), 5 is not directly in L2 (False) because it's nested inside a sublist, 6 is not in L1 (True), and [5,6] is directly in L2 (True)
- The comparison demonstrates how
inworks with nested structures - it checks for exact matches at the specified level of the list
Output
This code demonstrates how to iterate through lists using a for loop in Python.
Explanation
- The code initializes two lists, L1 and L2, containing integers and a nested list, respectively.
- The first for loop iterates through each element in L1, printing each integer from 1 to 5.
- The second for loop iterates through L2, printing each element, which includes integers and the nested list [5, 6].
- The nested list in L2 is printed as a single element, not unpacked, demonstrating how Python handles lists with varying structures.
Output
List Functions
This code snippet demonstrates basic list operations in Python to retrieve length, minimum, maximum, sorted order, and sum of elements.
Explanation
- The
len(L)function returns the number of elements in the listL. - The
min(L)function finds and returns the smallest element in the list. - The
max(L)function identifies and returns the largest element in the list. - The
sorted(L)function returns a new list containing all elements ofLsorted in ascending order. - The
sorted(L, reverse=True)function returns a new list with elements sorted in descending order. - The
sum(L)function calculates and returns the total sum of all elements in the list.
Output
This code snippet demonstrates how to count occurrences of specific elements in a list using Python.
Explanation
- The list
Lis initialized with several integers, including multiple occurrences of the number1. - The
count()method is called on the listLto determine how many times the integer1appears, which will return3. - A second call to
count()checks for the integer100, which is not present in the list, returning0. - The results of both
count()method calls are printed to the console.
Output
This code snippet demonstrates how to find the index of elements in a list using Python's index method.
Explanation
- The list
Lis initialized with integers, including multiple occurrences of the number1. - The
indexmethod is called on the listLto find the first occurrence of the element5, which returns its index. - The
indexmethod is then called again to find the first occurrence of the element1, returning the index of its first appearance in the list. - If the specified element is not found, a
ValueErrorwill be raised.
Output
This code snippet demonstrates how to permanently reverse a list in Python.
Explanation
- A list
Lis initialized with the elements[2, 1, 5, 7, 0]. - The
reverse()method is called on the listL, which modifies the list in place to reverse its order. - After the reversal, the list
Lwill contain the elements in the order[0, 7, 5, 1, 2]. - The
print()function outputs the reversed list to the console.
Output
Understanding the difference between the sort() method and the sorted() function in Python
Explanation
- The list
Lis initialized with unsorted integers. - The
sorted()function returns a new sorted list without modifying the original listL. - After calling
sorted(L), the original listLremains unchanged, which is demonstrated by the subsequent print statement. - The
sort()method sorts the list in place, modifyingLdirectly, and does not return a new list. - The final print statement shows the list
Lafter it has been sorted in place.
Output
Demonstrating shallow copying and reference assignment in Python lists
Explanation
- The code initializes a list
Lwith five integer elements and prints the list along with its memory address usingid(). - It creates a shallow copy of the list
Lusing thecopy()method, storing it inL1, and prints bothL1and its memory address. - The variable
L2is assigned to reference the same list object asL, and bothL2and its memory address are printed. - The difference in memory addresses between
L1andL2illustrates thatL1is a separate copy, whileL2is a reference to the original listL.
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.
This code snippet creates a list containing numbers from 1 to 10.
Explanation
- Initializes an empty list
Lto store the numbers. - Uses a
forloop to iterate over a range of numbers from 1 to 10. - Appends each number in the range to the list
L. - Finally, prints the list
L, which displays the numbers 1 through 10.
Output
This code snippet creates a list of numbers from 1 to 10 using list comprehension.
Explanation
- The code utilizes a list comprehension to generate a list of integers.
range(1, 11)generates numbers starting from 1 up to, but not including, 11.- Each number
iin the specified range is added to the listL. - Finally, the list
Lis printed, displaying the numbers from 1 to 10.
Output
Scalar multiplication of vectors using iterative multiplication and list appending
Explanation
- The code performs scalar multiplication by taking each element of the vector v and multiplying it by the scalar s
- It initializes an empty list x to store the results of the multiplication operations
- Through a for loop iteration over each element in the vector v, it multiplies each component by the scalar value -3
- The resulting multiplied values are appended to the new list x one at a time during each iteration
- Finally, the code outputs the complete transformed vector [-6, -9, -12] showing the effect of scaling the original vector by -3
Output
Scalar multiplication of vectors using list comprehension in Python
Explanation
- This code performs scalar multiplication by multiplying each element of vector v by scalar s
- The list comprehension [s*i for i in v] iterates through each component of the vector
- Each vector component (2, 3, 4) gets multiplied by the scalar (-3) to produce [-6, -9, -12]
- This demonstrates the mathematical operation of scaling a vector by a constant factor
- The result represents the original vector scaled by -3 in magnitude and direction
Output
Python list comprehension creates squared values from integer list
Explanation
- This code uses list comprehension syntax to generate a new list containing the square of each element from the original list
- The expression [i*i for i in L] iterates through each element in list L and applies the multiplication operation to create squared values
- The resulting list will contain [1, 4, 9, 16, 25] which are the squares of [1, 2, 3, 4, 5]
- This approach is more concise and readable than using traditional loops for simple transformations like this
- The original list L remains unchanged while a new list with squared values is created and returned
Output
Generate a list of numbers between 1 and 50 that are divisible by 5
Explanation
- Utilizes a list comprehension to create a new list.
- Iterates through numbers from 1 to 50 using
range(1, 51). - Applies a conditional check
if i % 5 == 0to filter numbers divisible by 5. - The result is a list containing only the numbers that meet the divisibility condition.
- Efficiently combines iteration and filtering in a single line of code.
Output
Filter a list to retrieve programming languages that begin with the letter 'p'
Explanation
- A list of programming languages is defined, containing various language names.
- A list comprehension is used to iterate through each language in the list.
- The
startswithmethod checks if each language starts with the letter 'p'. - The result is a new list containing only the languages that meet the condition.
Output
Filtering fruits based on existence in a basket and starting letter using list comprehension
Explanation
- The code initializes two lists:
basketcontaining available fruits andmy_fruitscontaining fruits to check. - A list comprehension is used to create a new list by iterating over
my_fruits. - It includes a fruit in the new list only if it exists in
basketand starts with the letter 'a'. - The resulting list will contain fruits that meet both conditions, effectively filtering
my_fruits. - This approach is concise and efficient for generating lists based on multiple criteria.
Output
Example 43
Explanation
- This code creates a 3x3 matrix using nested list comprehensions where each element is the product of its row and column indices
- The outer list comprehension iterates
jfrom 1 to 3 (representing rows), while the inner comprehension iteratesifrom 1 to 3 (representing columns) - Each matrix element at position (j,i) equals
j*i, creating multiplication table pattern - The result is a list of lists representing the matrix:
[[1, 2, 3], [2, 4, 6], [3, 6, 9]] - This demonstrates how nested list comprehensions can efficiently generate multi-dimensional data structures
Output
Generating Cartesian products using list comprehension in Python
Explanation
- This code snippet creates a Cartesian product of two lists,
L1andL2. - It uses a nested list comprehension to iterate over each element in
L1andL2. - For each combination of elements, it multiplies the elements together (
i * j). - The result is a new list containing the products of all combinations of elements from the two lists.
- The output will be a list of integers representing the products:
[5, 6, 7, 8, 10, 12, 14, 16, 15, 18, 21, 24].
Output
2 ways to traverse a list
- itemwise
- indexwise
This code snippet iterates through a list and prints each element individually.
Explanation
- A list
Lis defined containing four integer elements: 1, 2, 3, and 4. - A
forloop is used to iterate over each element in the listL. - During each iteration, the current element
iis printed to the console. - The output will display each number on a new line, resulting in a sequential display of the list elements.
Output
This code snippet iterates through a list and prints each index with its corresponding value.
Explanation
- A list
Lis defined containing four integer elements: 1, 2, 3, and 4. - A
forloop is used to iterate over the indices of the list, generated byrange(0, len(L)). - Inside the loop, the current index
iand the corresponding valueL[i]are printed in the format "index - value". - The output will display each index of the list alongside its respective element, providing a clear mapping of indices to values.
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.
This code snippet demonstrates how to add corresponding elements of two lists in Python.
Explanation
- The code initializes two lists,
L1andL2, containing integers. - It uses the
zipfunction to pair elements from both lists index-wise. - A list comprehension iterates over the zipped pairs, summing each pair of elements (
ifromL1andjfromL2). - The result is a new list containing the sums of corresponding elements from the two input lists.
- The final output will be
[6, 8, 10, 12], representing the sums of the pairs (1+5, 2+6, 3+7, 4+8).
Output
This code snippet iterates through a list of pairs and prints their sums.
Explanation
- The code uses a for loop to iterate over a list containing two sublists, each with two integers.
- The loop unpacks each sublist into variables
iandj. - For each pair, it calculates the sum of
iandj. - The result of the sum is printed to the console for each iteration.
- The output will be the sums of the pairs: 3 (1+2) and 7 (3+4).
Output
This code snippet demonstrates how to create a list containing various Python objects, including functions.
Explanation
- A list
Lis created containing integers and built-in functions:print,type, andinput. - The
printfunction is included as an object in the list, which means it can be referenced but not executed directly within the list. - When
print(L)is called, it outputs the entire list, showing the objects it contains, including their representations. - The inclusion of functions in the list illustrates Python's first-class function capability, allowing functions to be treated as objects.
- The output will display the list with the function references, not their results or outputs.
Output
Disadvantages of Python Lists
- Slow
- Risky usage
- eats up more memory
Understanding list assignment and mutability in Python
Explanation
- The variable
ais initialized as a list containing the elements[1, 2, 3]. - The variable
bis assigned toa, meaning bothaandbreference the same list object in memory. - When
4is appended toa, it modifies the original list, which is reflected in bothaandbsince they point to the same object. - The output demonstrates that changes to one variable affect the other due to the mutable nature of lists in Python.
- This behavior highlights the importance of understanding variable assignment and object references in Python programming.
Output
Demonstrating list copying and mutation effects in Python
Explanation
- The code initializes a list
awith three integers: 1, 2, and 3. - It creates a shallow copy of the list
ainto a new listbusing thecopy()method. - The original list
ais printed, followed by the copied listb, showing they are identical at this point. - An integer 4 is appended to the original list
a, modifying it. - Finally, both lists are printed again, illustrating that
bremains unchanged whileareflects the addition of the new element.
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:
Combining two lists into tuples and lists using zip in Python
Explanation
- The
zipfunction pairs elements fromlist1andlist2, creating tuples for each corresponding element. - The first
printstatement outputs a list of tuples, where each tuple contains one element fromlist1and one fromlist2. - The second
printstatement uses a list comprehension to create a list of lists instead of tuples, maintaining the same pairing of elements. - Both outputs demonstrate how to efficiently combine multiple lists in Python using
zip.
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:
Modifying a nested list in Python by appending a value to an inner list
Explanation
- The code initializes a nested list
list1containing integers and other lists. - It accesses the innermost list located at
list1[2][2], which is[5000, 6000]. - The
appendmethod is used to add the value7000to this innermost list. - Finally, the modified
list1is printed, showing the updated structure with7000included. - This demonstrates how to manipulate complex data structures in Python effectively.
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:
This code pairs candy names with their respective quantities and prints them in a formatted manner.
Explanation
- The
candy_listcontains names of different candies, whileno_of_itemsholds the corresponding quantities for each candy. - The
zipfunction combines both lists into pairs, creating a list of tuples where each tuple contains a candy name and its quantity. - The
printstatement outputs the list of tuples, showing the candy names alongside their quantities. - A list comprehension is used to iterate through the zipped pairs, printing each candy name and quantity in a formatted way, separated by a hyphen.
- The use of
sep='-'in theprintfunction customizes the output format for better readability.
Output
###Problem 4: Running Sum on list
Write a program to print a list after performing running sum on it.
i.e:
Input:
Output:
This code calculates the cumulative sum of a list of integers.
Explanation
- Initializes a list
list1containing integers from 1 to 6. - Sets a variable
sumto 0 to keep track of the cumulative total. - Creates an empty list
resultto store the cumulative sums. - Iterates through each integer in
list1, updatingsumand appending the current cumulative total toresult. - Finally, prints the
resultlist, which contains the cumulative sums at each step.
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]
Calculate cumulative sums of elements in a list based on their values
Explanation
- Initializes a list
Lcontaining integers and an empty listresultto store cumulative sums. - Iterates through each element
iin the listL. - For each
i, it initializes asumvariable to zero and iterates through the listLagain. - If the current element
jis greater than or equal toi, it addsjto thesum. - Appends the calculated
sumfor eachito theresultlist, which is printed at the end.
Output
###Problem 6: Find list of common unique items from two list. and show in increasing order
Input
Output:
This code identifies and sorts common elements between two lists of numbers.
Explanation
- Initializes two lists,
num1andnum2, containing integer values. - Creates an empty list
resultto store common elements found in bothnum1andnum2. - Iterates through each element in
num1and checks if it exists innum2. - If a common element is found, it is appended to the
resultlist. - Finally, the
resultlist is sorted and printed, displaying the common elements in ascending order.
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:
Python script to sort strings by the product of their numeric characters in descending order
Explanation
- The code processes a list of mixed alphanumeric strings to calculate the product of all numeric digits in each string
- It iterates through each string and multiplies together all digit characters found within that string
- The results are paired with original strings and sorted in descending order based on the calculated products
- The final output displays both the sorted pairs and just the original strings in the new sorted order
- Strings containing no digits result in a product of 1, which affects their relative positioning in the final sorted list
Output
Problem 8: Split String of list on K character.
Example :
Input:
Output:
Python code demonstrating string splitting and list extension operations on a list of sentences
Explanation
- The code initializes a list of strings containing phrases with spaces as delimiters
- It iterates through each string in the list and splits it by whitespace using the split() method
- The extend() method appends all elements from the split operation to the result list
- Each string gets broken down into individual words and added to the final result list
- The output displays all words from the original strings as separate elements in a single list
Output
Problem 9: Convert Character Matrix to single String using string comprehension.
Example 1:
Input:
Output:
Python list comprehension joins nested lists into strings and combines them with spaces
Explanation
- The code defines a nested list L containing four sublists of characters representing words
- The first print statement uses list comprehension to join each sublist into a string, creating a list of words: ['campux', 'is', 'best', 'channel']
- The second print statement joins all the resulting words from the first operation with spaces between them: "campux is best channel"
- This demonstrates how nested list comprehensions can transform multi-dimensional data structures into readable text formats
- The approach efficiently converts character-based data into meaningful string representations through sequential joining operations
Output
Problem 10: Add Space between Potential Words.
Example:
Input:
Output:
This code separates uppercase letters from words and formats them into strings.
Explanation
- Initializes a list
Lcontaining words with mixed case letters. - Iterates through each word in the list, creating a temporary list
tempto group characters based on uppercase letters. - For each character in the word, it checks if the character is uppercase; if so, it starts a new sublist in
temp. - Constructs a formatted string from the grouped characters and appends it to the
resultlist after removing the trailing space. - Finally, prints the
resultlist containing the formatted strings for each word.
Output
Problem 11: Write a program that can perform union operation on 2 lists
Example:
Input:
Output:
Merging two lists into a unique union of elements in Python
Explanation
- Initializes two lists, L1 and L2, containing integers with some overlapping values.
- Creates an empty list called 'union' to store unique elements from both lists.
- Iterates through the first list (L1) and appends each element to 'union' if it is not already present.
- Repeats the process for the second list (L2), ensuring only unique elements are added to 'union'.
- Finally, prints the 'union' list, which contains all unique elements from both L1 and L2.
Output
Problem 12: Write a program that can find the max number of each row of a matrix
Example:
Input:
Output:
This code extracts the maximum value from each sublist in a nested list structure.
Explanation
- A nested list
Lis defined containing three sublists, each with three integers. - An empty list
resultis initialized to store the maximum values. - A for loop iterates through each sublist in
L, applying themax()function to find the highest number in each sublist. - The maximum value from each sublist is appended to the
resultlist. - Finally, the
resultlist, containing the maximum values from each sublist, is printed.
Output
Problem 13: Write a list comprehension to print the following matrix
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
Generate a 2D list using nested list comprehension in Python
Explanation
- The code creates a 3x3 matrix (list of lists) using nested list comprehension.
- The outer loop iterates over the range from 0 to 2 (inclusive) for the variable
i. - The inner loop iterates over the range from 0 to 2 (inclusive) for the variable
j. - Each element of the matrix is calculated as
j + 3*i, which results in a unique value for each position based on its row and column. - The final output is a list containing three lists, each representing a row of the matrix.
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]
This code transposes a 3x3 matrix by swapping its rows and columns.
Explanation
- The
matrixvariable is defined as a 3x3 list of lists, representing a grid of numbers. - The outer list comprehension iterates over the range of the matrix's length, which is 3 in this case, corresponding to the number of columns.
- The inner list comprehension retrieves the
i-th element from each row, effectively collecting all elements in thei-th column. - The result is a new list of lists that represents the transposed version of the original matrix, where rows become columns and vice versa.
- The final output will be
[[1, 4, 7], [2, 5, 8], [3, 6, 9]], which is the transposed matrix.
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]
This code iterates through a 2D list and prints each element in a single line.
Explanation
- A 2D list named
matrixis defined, containing three rows and three columns of integers. - The first nested loop iterates through each
rowin thematrix. - The inner loop iterates through each
itemin the currentrow, printing each item followed by a space. - The list comprehension at the end flattens the 2D list into a 1D list, collecting all items from the
matrix.
Output
Next in this series: Python Tuples, Sets & Dictionaries: A Complete Guide →

