Skip to content
Cover image for: Python Lists: Creation, Manipulation & Use
#pythonBeginner

Python Lists: Creation, Manipulation & Use

Apr 30, 2026
Updated May 14, 2026
30 min read

AI Insights

Powered by GPT-4o-mini

Verified Context: python-lists-creation-manipulation-use

Master Python lists in depth with creation, indexing (positive and negative), slicing with steps, all built-in methods (append, extend, insert, remove, pop, sort, reverse), list comprehensions with conditional filtering, nested lists for matrix operations, sorting with custom key functions, shallow vs deep copying with copy module, and Big O performance analysis for common list operations including append, insert, lookup, and delete with practical examples.

Quick Summary

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.

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
python

Output

text

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
python

Output

text

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
python

Output

text

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.
python

Output

text

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].
python

Output

text

Adding Items to a List

This code demonstrates how to add elements to a list in Python.

Explanation

  • A list L is initialized with five integer elements: 1, 2, 3, 4, and 5.
  • The append method is used to add the integer 6 to the end of the list.
  • The append method is then used again to add the boolean value True to the list.
  • Finally, the updated list L is printed, displaying all its elements including the newly added ones.
python

Output

text

This code snippet demonstrates how to extend a list in Python by adding multiple elements at once.

Explanation

  • The list L is initialized with five integer elements: 1, 2, 3, 4, and 5.
  • The extend() method is called on the list L, 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.
python

Output

text

This code demonstrates how to append a list to another list in Python.

Explanation

  • A list L is 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 list L.
  • 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 L will be [1, 2, 3, 4, 5, [6, 7, 8]], showcasing that the appended list is nested within the original list.
python

Output

text

This code demonstrates how to extend a list with characters from a string in Python.

Explanation

  • The list L is initialized with five integer elements: 1, 2, 3, 4, and 5.
  • The extend method is called on the list L with the string 'delhi', which adds each character of the string as separate elements to the list.
  • After the extension, the list L will contain both the original integers and the individual characters from the string.
  • The print function outputs the modified list, showing the result of the extension operation.
python

Output

text

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
python

Output

text

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
python

Output

text

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
python

Output

text

This code demonstrates how to insert an element into a specific position in a Python list.

Explanation

  • A list L is initialized with five integer elements: [1, 2, 3, 4, 5].
  • The insert method is called on the list L to add the integer 100 at index 1, 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.
python

Output

text

This code snippet demonstrates how to insert an element into a specific position in a Python list.

Explanation

  • A list L is initialized with five integer elements: [1, 2, 3, 4, 5].
  • The insert method is called on the list L to add the string 'delhi' at index 1, 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.
python

Output

text

Editing Items in a List

This code modifies the last element of a list and prints the updated list.

Explanation

  • A list L is 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.
python

Output

text

This code snippet demonstrates how to modify a portion of a list in Python using slicing.

Explanation

  • A list L is 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].
python

Output

text

Deleting Items from a List

Example 17

Explanation

  • The code creates a list L with values [1,2,3,4,5] and prints it
  • The del statement is used to delete the entire list variable L from memory
  • After deletion, attempting to print L raises a NameError because the variable no longer exists
  • This demonstrates how del removes variables entirely rather than just clearing their contents
  • Expected output shows the list printed once, then crashes with NameError on second print attempt
python

Output

text

This code demonstrates how to remove an element from a list in Python using the del statement.

Explanation

  • A list L is initialized with five integer elements: [1, 2, 3, 4, 5].
  • The original list is printed to the console.
  • The del statement is used to remove the element at index 2, which corresponds to the value 3.
  • The modified list is printed, showing the updated contents: [1, 2, 4, 5].
python

Output

text

Example 19

Explanation

  • The code demonstrates the del statement in Python, which removes elements from a list by index
  • It first creates a list L with 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
python

Output

text

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
python

Output

text

This code demonstrates how to remove an element from a list using the pop method in Python.

Explanation

  • The list L is 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 is 1).
  • After the pop operation, the list L is modified to [2, 3, 4, 5].
  • The print(L) statement outputs the updated list to the console.
  • The pop method can also be used to remove elements from other indices by providing a different index as an argument.
python

Output

text

This code snippet demonstrates how to remove the last element from a list in Python using the pop method.

Explanation

  • The list L is initialized with five integer elements: 1, 2, 3, 4, and 5.
  • The pop() method is called on the list L, 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.
python

Output

text

This code snippet demonstrates how to clear a list in Python using the clear() method.

Explanation

  • The list L is initialized with five integer elements: 1, 2, 3, 4, and 5.
  • The clear() method is called on the list L, 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.
python

Output

text

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 print function outputs the merged list to the console, displaying the combined elements in order.
python

Output

text

This code snippet demonstrates how to repeat a list multiple times in Python.

Explanation

  • The code uses the print function to output the result of the operation.
  • L1 is expected to be a list defined earlier in the code.
  • The * operator is used to repeat the list L1 three times.
  • The output will be a new list containing the elements of L1 concatenated three times.
  • If L1 is empty, the output will also be an empty list.
python

Output

text

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.
python

Output

text

Example 27

Explanation

  • The code creates two lists L1 and L2 with nested structure, then tests membership and non-membership operations using in and not in operators
  • Key APIs used: in operator to check if elements exist in lists, not in operator to check if elements don't exist in lists
  • The in operator 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 in works with nested structures - it checks for exact matches at the specified level of the list
python

Output

text

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.
python

Output

text

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 list L.
  • 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 of L sorted 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.
python

Output

text

This code snippet demonstrates how to count occurrences of specific elements in a list using Python.

Explanation

  • The list L is initialized with several integers, including multiple occurrences of the number 1.
  • The count() method is called on the list L to determine how many times the integer 1 appears, which will return 3.
  • A second call to count() checks for the integer 100, which is not present in the list, returning 0.
  • The results of both count() method calls are printed to the console.
python

Output

text

This code snippet demonstrates how to find the index of elements in a list using Python's index method.

Explanation

  • The list L is initialized with integers, including multiple occurrences of the number 1.
  • The index method is called on the list L to find the first occurrence of the element 5, which returns its index.
  • The index method is then called again to find the first occurrence of the element 1, returning the index of its first appearance in the list.
  • If the specified element is not found, a ValueError will be raised.
python

Output

text

This code snippet demonstrates how to permanently reverse a list in Python.

Explanation

  • A list L is initialized with the elements [2, 1, 5, 7, 0].
  • The reverse() method is called on the list L, which modifies the list in place to reverse its order.
  • After the reversal, the list L will contain the elements in the order [0, 7, 5, 1, 2].
  • The print() function outputs the reversed list to the console.
python

Output

text

Understanding the difference between the sort() method and the sorted() function in Python

Explanation

  • The list L is initialized with unsorted integers.
  • The sorted() function returns a new sorted list without modifying the original list L.
  • After calling sorted(L), the original list L remains unchanged, which is demonstrated by the subsequent print statement.
  • The sort() method sorts the list in place, modifying L directly, and does not return a new list.
  • The final print statement shows the list L after it has been sorted in place.
python

Output

text

Demonstrating shallow copying and reference assignment in Python lists

Explanation

  • The code initializes a list L with five integer elements and prints the list along with its memory address using id().
  • It creates a shallow copy of the list L using the copy() method, storing it in L1, and prints both L1 and its memory address.
  • The variable L2 is assigned to reference the same list object as L, and both L2 and its memory address are printed.
  • The difference in memory addresses between L1 and L2 illustrates that L1 is a separate copy, while L2 is a reference to the original list L.
python

Output

text

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 L to store the numbers.
  • Uses a for loop 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.
python

Output

text

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 i in the specified range is added to the list L.
  • Finally, the list L is printed, displaying the numbers from 1 to 10.
python

Output

text

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
python

Output

text

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
python

Output

text

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
python

Output

text

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 == 0 to 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.
python

Output

text

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 startswith method checks if each language starts with the letter 'p'.
  • The result is a new list containing only the languages that meet the condition.
python

Output

text

Filtering fruits based on existence in a basket and starting letter using list comprehension

Explanation

  • The code initializes two lists: basket containing available fruits and my_fruits containing 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 basket and 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.
python

Output

text

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 j from 1 to 3 (representing rows), while the inner comprehension iterates i from 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
python

Output

text

Generating Cartesian products using list comprehension in Python

Explanation

  • This code snippet creates a Cartesian product of two lists, L1 and L2.
  • It uses a nested list comprehension to iterate over each element in L1 and L2.
  • 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].
python

Output

text

2 ways to traverse a list

  • itemwise
  • indexwise

This code snippet iterates through a list and prints each element individually.

Explanation

  • A list L is defined containing four integer elements: 1, 2, 3, and 4.
  • A for loop is used to iterate over each element in the list L.
  • During each iteration, the current element i is printed to the console.
  • The output will display each number on a new line, resulting in a sequential display of the list elements.
python

Output

text

This code snippet iterates through a list and prints each index with its corresponding value.

Explanation

  • A list L is defined containing four integer elements: 1, 2, 3, and 4.
  • A for loop is used to iterate over the indices of the list, generated by range(0, len(L)).
  • Inside the loop, the current index i and the corresponding value L[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.
python

Output

text

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, L1 and L2, containing integers.
  • It uses the zip function to pair elements from both lists index-wise.
  • A list comprehension iterates over the zipped pairs, summing each pair of elements (i from L1 and j from L2).
  • 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).
python

Output

text

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 i and j.
  • For each pair, it calculates the sum of i and j.
  • 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).
python

Output

text

This code snippet demonstrates how to create a list containing various Python objects, including functions.

Explanation

  • A list L is created containing integers and built-in functions: print, type, and input.
  • The print function 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.
python

Output

text

Disadvantages of Python Lists

  • Slow
  • Risky usage
  • eats up more memory

Understanding list assignment and mutability in Python

Explanation

  • The variable a is initialized as a list containing the elements [1, 2, 3].
  • The variable b is assigned to a, meaning both a and b reference the same list object in memory.
  • When 4 is appended to a, it modifies the original list, which is reflected in both a and b since 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.
python

Output

text

Demonstrating list copying and mutation effects in Python

Explanation

  • The code initializes a list a with three integers: 1, 2, and 3.
  • It creates a shallow copy of the list a into a new list b using the copy() method.
  • The original list a is printed, followed by the copied list b, 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 b remains unchanged while a reflects the addition of the new element.
python

Output

text

###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:

text

Output:

text

Combining two lists into tuples and lists using zip in Python

Explanation

  • The zip function pairs elements from list1 and list2, creating tuples for each corresponding element.
  • The first print statement outputs a list of tuples, where each tuple contains one element from list1 and one from list2.
  • The second print statement 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.
python

Output

text

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

text

Output:

text

Modifying a nested list in Python by appending a value to an inner list

Explanation

  • The code initializes a nested list list1 containing integers and other lists.
  • It accesses the innermost list located at list1[2][2], which is [5000, 6000].
  • The append method is used to add the value 7000 to this innermost list.
  • Finally, the modified list1 is printed, showing the updated structure with 7000 included.
  • This demonstrates how to manipulate complex data structures in Python effectively.
python

Output

text

###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 -

text

Write a program to show no. of items of each candy type.

Output:

text

This code pairs candy names with their respective quantities and prints them in a formatted manner.

Explanation

  • The candy_list contains names of different candies, while no_of_items holds the corresponding quantities for each candy.
  • The zip function combines both lists into pairs, creating a list of tuples where each tuple contains a candy name and its quantity.
  • The print statement 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 the print function customizes the output format for better readability.
python

Output

text

###Problem 4: Running Sum on list Write a program to print a list after performing running sum on it.

i.e:

Input:

text

Output:

text

This code calculates the cumulative sum of a list of integers.

Explanation

  • Initializes a list list1 containing integers from 1 to 6.
  • Sets a variable sum to 0 to keep track of the cumulative total.
  • Creates an empty list result to store the cumulative sums.
  • Iterates through each integer in list1, updating sum and appending the current cumulative total to result.
  • Finally, prints the result list, which contains the cumulative sums at each step.
python

Output

text

###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 L containing integers and an empty list result to store cumulative sums.
  • Iterates through each element i in the list L.
  • For each i, it initializes a sum variable to zero and iterates through the list L again.
  • If the current element j is greater than or equal to i, it adds j to the sum.
  • Appends the calculated sum for each i to the result list, which is printed at the end.
python

Output

text

###Problem 6: Find list of common unique items from two list. and show in increasing order

Input

text

Output:

text

This code identifies and sorts common elements between two lists of numbers.

Explanation

  • Initializes two lists, num1 and num2, containing integer values.
  • Creates an empty list result to store common elements found in both num1 and num2.
  • Iterates through each element in num1 and checks if it exists in num2.
  • If a common element is found, it is appended to the result list.
  • Finally, the result list is sorted and printed, displaying the common elements in ascending order.
python

Output

text

###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:

text

Output:

text

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
python

Output

text

Problem 8: Split String of list on K character.

Example :

Input:

bash

Output:

bash

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
python

Output

text

Problem 9: Convert Character Matrix to single String using string comprehension.

Example 1:

Input:

bash

Output:

bash

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
python

Output

text

Problem 10: Add Space between Potential Words.

Example:

Input:

bash

Output:

bash

This code separates uppercase letters from words and formats them into strings.

Explanation

  • Initializes a list L containing words with mixed case letters.
  • Iterates through each word in the list, creating a temporary list temp to 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 result list after removing the trailing space.
  • Finally, prints the result list containing the formatted strings for each word.
python

Output

text

Problem 11: Write a program that can perform union operation on 2 lists

Example:

Input:

bash

Output:

bash

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.
python

Output

text

Problem 12: Write a program that can find the max number of each row of a matrix

Example:

Input:

bash

Output:

bash

This code extracts the maximum value from each sublist in a nested list structure.

Explanation

  • A nested list L is defined containing three sublists, each with three integers.
  • An empty list result is initialized to store the maximum values.
  • A for loop iterates through each sublist in L, applying the max() function to find the highest number in each sublist.
  • The maximum value from each sublist is appended to the result list.
  • Finally, the result list, containing the maximum values from each sublist, is printed.
python

Output

text

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.
python

Output

text

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 matrix variable 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 the i-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.
python

Output

text

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 matrix is defined, containing three rows and three columns of integers.
  • The first nested loop iterates through each row in the matrix.
  • The inner loop iterates through each item in the current row, 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.
python

Output

text

Next in this series: Python Tuples, Sets & Dictionaries: A Complete Guide →

Frequently Asked Questions

Lists in Python are ordered, changeable/mutable, heterogeneous, can have duplicates, are dynamic, can be nested, and can contain any kind of objects.
Unlike arrays, lists are dynamic in size and can store heterogeneous data types, offering more convenience and flexibility in programming.
Python assigns unique memory addresses to objects, and list elements share the same memory address as their corresponding literal values, showcasing object reuse optimization.
Python uses the equality operator '==' to check if two lists have the same elements in the exact same sequence, meaning order matters in the comparison.
An empty list can be created using square brackets with no elements, demonstrating the basic syntax for initializing empty collections.

How was this tutorial?

Python Lists: Creation, Manipulation & Use | Madhu Dadi