Category: Lists

  • List Exercises

    Python List Exercise 1

    Python program to find unique numbers in a given list.

    L1 =[1,9,1,6,3,4,5,1,1,2,5,6,7,8,9,2]
    L2 =[]for x in L1:if x notin L2:
    
      L2.append(x)print(L2)</pre>

    It will produce the following output −

    [1, 9, 6, 3, 4, 5, 2, 7, 8]

    Python List Exercise 2
    Python program to find sum of all numbers in a list.

    L1 = [1, 9, 1, 6, 3, 4]
    ttl = 0
    for x in L1:
    ttl+=x
    print ("Sum of all numbers Using loop:", ttl)
    ttl = sum(L1)
    print ("Sum of all numbers sum() function:", ttl)
    It will produce the following output −

    Sum of all numbers Using loop: 24
    Sum of all numbers sum() function: 24
    Python List Exercise 3
    Python program to create a list of 5 random integers.

    import random
    L1 = []
    for i in range(5):
    x = random.randint(0, 100)
    L1.append(x)
    print (L1)
    It will produce the following output −

    [77, 3, 20, 91, 85]
  • List Methods

    List is one of the fundamental data structures in Python, It provides a flexible way to store and manage a collection of items. It has several built-in methods that allow you to add, update, and delete items efficiently.

    Lists in Python can contain items of different data types, including other lists, making them highly flexible to different scenarios. The list object includes several built-in methods that allow you to add, update, and delete items efficiently, as well as to perform various operations on the list’s elements.

    Python List Methods

    The list methods enable you to manipulate lists easily and effectively, whether you are appending new items, removing existing ones, or even sorting and reversing the list. By using these built-in methods, you can work with lists in Python more effectively, allowing you to write more efficient and readable code.

    Printing All the List Methods

    To view all the available methods for lists, you can use the Python dir() function, which returns all the properties and functions related to an object. Additionally, you can use the Python help() function to get more detailed information about each method. For example:

    print(dir([]))print(help([].append))

    The above code snippet provides a complete list of properties and functions related to the list class. It also demonstrates how to access detailed documentation for a specific method in your Python environment. Here is the output −

    ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
    Help on built-in function append:
    
    append(object, /) method of builtins.list instance
    
    Append object to the end of the list.
    (END)

    Below, the built-in methods for lists in Python, which are categorized based on their functionality. Let’s explore and understand the basic fuctionality of each method.

    Methods to Add Elements to a List

    The following are the methods specifically designed for adding new item/items into a list −

    Sr.No.Methods with Description
    1list.append(obj)Appends object obj to list.
    2list.extend(seq)Appends the contents of seq to list
    3list.insert(index, obj)Inserts object obj into list at offset index

    Methods to Remove Elements from a List

    The following are the methods specifically designed for removing items from a list −

    Sr.No.Methods with Description
    1list.clear()Clears all the contents of the list.
    2list.pop(obj=list[-1])Removes and returns the last object or the object at the specified index from the list.
    3list.remove(obj)Removes the first occurrence of object obj from the list.

    Methods to Access Elements in a List

    These are the methods used for finding or counting items in a list −

    Sr.No.Methods with Description
    1list.index(obj)Returns the lowest index in list that obj appears
    2list.count(obj)Returns count of how many times obj occurs in the list.

    Copying and Ordering Methods

    These are the methods used for creating copies and arranging items in a list −

    Sr.No.Methods with Description
    1list.copy()Returns a copy of the list object.
    2list.sort([func])Sorts the objects in the list in place, using a comparison function if provided.
    3list.reverse()Reverses the order of objects in the list in place.
  •  Join Lists

    Join Lists in Python

    Joining lists in Python refers to combining the elements of multiple lists into a single list. This can be achieved using various methods, such as concatenation, list comprehension, or using built-in functions like extend() or + operator.

    Joining lists does not modify the original lists but creates a new list containing the combined elements.

    Join Lists Using Concatenation Operator

    The concatenation operator in Python, denoted by +, is used to join two sequences, such as strings, lists, or tuples, into a single sequence. When applied to lists, the concatenation operator joins the elements of the two (or more) lists to create a new list containing all the elements from both lists.

    We can join a list using the concatenation operator by simply using the + symbol to concatenate the lists.

    Example

    In the following example, we are concatenating the elements of two lists “L1” and “L2”, creating a new list “joined_list” containing all the elements from both lists −

    # Two lists to be joined
    L1 =[10,20,30,40]
    L2 =['one','two','three','four']# Joining the lists
    joined_list = L1 + L2
    
    # Printing the joined listprint("Joined List:", joined_list)

    Following is the output of the above code −

    Joined List: [10, 20, 30, 40, 'one', 'two', 'three', 'four']
    

    Join Lists Using List Comprehension

    List comprehension is a concise way to create lists in Python. It is used to generate new lists by applying an expression to each item in an existing iterable, such as a list, tuple, or range. The syntax for list comprehension is −

    new_list =[expression for item in iterable]

    This creates a new list where expression is evaluated for each item in the iterable.

    We can join a list using list comprehension by iterating over multiple lists and appending their elements to a new list.

    Example

    In this example, we are joining two lists, L1 and L2, into a single list using list comprehension. The resulting list, joined_list, contains all elements from both L1 and L2 −

    # Two lists to be joined
    L1 =[36,24,3]
    L2 =[84,5,81]# Joining the lists using list comprehension
    joined_list =[item for sublist in[L1, L2]for item in sublist]# Printing the joined listprint("Joined List:", joined_list)

    Output of the above code is as follows −

    Joined List: [36, 24, 3, 84, 5, 81]
    

    Join Lists Using append() Function

    The append() function in Python is used to add a single element to the end of a list. This function modifies the original list by adding the element to the end of the list.

    We can join a list using the append() function by iterating over the elements of one list and appending each element to another list.

    Example

    In the example below, we are appending elements from “list2” to “list1” using the append() function. We achieve this by iterating over “list2” and adding each element to “list1” −

    # List to which elements will be appended
    list1 =['Fruit','Number','Animal']# List from which elements will be appended
    list2 =['Apple',5,'Dog']# Joining the lists using the append() functionfor element in list2:
    
    list1.append(element)# Printing the joined listprint("Joined List:", list1)</pre>

    We get the output as shown below −

    Joined List: ['Fruit', 'Number', 'Animal', 'Apple', 5, 'Dog']
    

    Join Lists Using extend() Function

    The Python extend() function is used to append elements from an iterable (such as another list) to the end of the list. This function modifies the original list in place, adding the elements of the iterable to the end of the list.

    We can join a list using the extend() function by calling it on one list and passing another list (or any iterable) as an argument. This will append all the elements from the second list to the end of the first list.

    Example

    In the following example, we are extending "list1" by appending the elements of "list2" using the extend() function −

    # List to be extended
    list1 =[10,15,20]# List to be added
    list2 =[25,30,35]# Joining the lists using the extend() function
    list1.extend(list2)# Printing the extended listprint("Extended List:", list1)

    The output obtained is as shown below −

    Extended List: [10, 15, 20, 25, 30, 35]
    
  • Copy Lists

    Copying a List in Python

    Copying a list in Python refers to creating a new list that contains the same elements as the original list. There are different methods for copying a list, including, using slice notation, the list() function, and using the copy() method.

    Each method behaves differently in terms of whether it creates a shallow copy or a deep copy. Let us discuss about all of these deeply in this tutorial.

    Shallow Copy on a Python List

    A shallow copy in Python creates a new object, but instead of copying the elements recursively, it copies only the references to the original elements. This means that the new object is a separate entity from the original one, but if the elements themselves are mutable, changes made to those elements in the new object will affect the original object as well.

    Example of Shallow Copy

    Let us illustrate this with the following example −

    Open Compiler

    import copy
    # Original list
    original_list =[[1,2,3],[4,5,6],[7,8,9]]# Creating a shallow copy
    shallow_copied_list = copy.copy(original_list)# Modifying an element in the shallow copied list
    shallow_copied_list[0][0]=100# Printing both listsprint("Original List:", original_list)print("Shallow Copied List:", shallow_copied_list)

    As you can see, even though we only modified the first element of the first sublist in the shallow copied list, the same change is reflected in the original list as well.

    This is because a shallow copy only creates new references to the original objects, rather than creating copies of the objects themselves −

    Original List: [[100, 2, 3], [4, 5, 6], [7, 8, 9]]
    Shallow Copied List: [[100, 2, 3], [4, 5, 6], [7, 8, 9]]
    

    Deep Copy on a Python List

    A deep copy in Python creates a completely new object and recursively copies all the objects referenced by the original object. This means that even nested objects within the original object are duplicated, resulting in a fully independent copy where changes made to the copied object do not affect the original object, and vice versa.

    Example of Deep Copy

    Let us illustrate this with the following example −

    Open Compiler

    import copy
    # Original list
    original_list =[[1,2,3],[4,5,6],[7,8,9]]# Creating a deep copy
    deep_copied_list = copy.deepcopy(original_list)# Modifying an element in the deep copied list
    deep_copied_list[0][0]=100# Printing both listsprint("Original List:", original_list)print("Deep Copied List:", deep_copied_list)

    As you can see, when we modify the first element of the first sublist in the deep copied list, it does not affect the original list.

    This is because a deep copy creates a new object and recursively copies all the nested objects, ensuring that the copied object is fully independent from the original one −

    Original List: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    Deep Copied List: [[100, 2, 3], [4, 5, 6], [7, 8, 9]]
    

    Copying List Using Slice Notation

    Slice notation in Python allows you to create a subsequence of elements from a sequence (like a list, tuple, or string) by specifying a start index, an end index, and an optional step size. The syntax for slice notation is as follows −

    [start:end:step]

    Where, start is the index where the slice starts, end is the index where the slice ends (exclusive), and step is the step size between elements.

    We can copy a list using slice notation by specifying the entire range of indices of the original list. This effectively creates a new list with the same elements as the original list.

    Any modifications made to the copied list will not affect the original list, and vice versa, because they are separate objects in memory.

    Example

    In this example, we are creating a slice of the “original_list”, effectively copying all its elements into a new list “copied_list” −

    # Original list
    original_list =[1,2,3,4,5]# Copying the list using slice notation
    copied_list = original_list[1:4]# Modifying the copied list
    copied_list[0]=100# Printing both listsprint("Original List:", original_list)print("Copied List:", copied_list)

    We get the result as shown below −

    Original List: [1, 2, 3, 4, 5]
    Copied List: [100, 3, 4]
    

    Copying List Using the list() Function

    The list() function in Python is a built-in function used to create a new list object. It can accept an iterable (like another list, tuple, set, etc.) as an argument and create a new list containing the elements of that iterable. If no argument is provided, an empty list is created.

    We can copy a list using the list() function by passing the original list as an argument. This will create a new list object containing the same elements as the original list.

    Example

    In the example below, we are creating a new list object “copied_list” containing the same elements as “original_list” using the list() function −

    # Original list
    original_list =[1,2,3,4,5]# Copying the list using the list() constructor
    copied_list =list(original_list)# Printing both listsprint("Original List:", original_list)print("Copied List:", copied_list)

    Following is the output of the above code −

    Original List: [1, 2, 3, 4, 5]
    Copied List: [1, 2, 3, 4, 5]
    

    Copying List Using the copy() Function

    In Python, the copy() function is used to create a shallow copy of a list or other mutable objects. This function is part of the copy module in Python’s standard library.

    We can copy a list using the copy() function by invoking it on the original list. This creates a new list object that contains the same elements as the original list.

    Example

    In the following example, we are using the copy() function to creates a new list object “copied_list” containing the same elements as “original_list” −

    import copy
    original_list =[1,2,3,4,5]# Copying the list using the copy() function
    copied_list = copy.copy(original_list)print("Copied List:", copied_list)

    Output of the above code is as shown below −

    Copied List: [1, 2, 3, 4, 5]
  •  Sort Lists

    Sorting Lists in Python

    Sorting a list in Python is a way to arrange the elements of the list in either ascending or descending order based on a defined criterion, such as numerical or lexicographical order.

    This can be achieved using the built-in sorted() function or by calling the sort() method on the list itself, both of which modify the original list or return a new sorted list depending on the method used.

    Sorting Lists Using sort() Method

    The python sort() method is used to sort the elements of a list in place. This means that it modifies the original list and does not return a new list.

    Syntax

    The syntax for using the sort() method is as follows −

    list_name.sort(key=None, reverse=False)

    Where,

    • list_name is the name of the list to be sorted.
    • key (optional) is a function that defines the sorting criterion. If provided, it is applied to each element of the list for sorting. Default is None.
    • reverse (optional) is a boolean value. If True, the list will be sorted in descending order. If False (default), the list will be sorted in ascending order.

    Example of Sorting List in Lexicographical Order

    In the following example, we are using the sort() function to sort the items of the list alphanumerically −

    list1 =['physics','Biology','chemistry','maths']print("list before sort:", list1)
    list1.sort()print("list after sort : ", list1)

    It will produce the following output −

    list before sort: ['physics', 'Biology', 'chemistry', 'maths']
    list after sort :  ['Biology', 'chemistry', 'maths', 'physics']
    

    Example of Sorting List in Numerical Order

    In here, we are using the sort() function to sort the given list in numerical order −

    list2 =[10,16,9,24,5]print("list before sort", list2)
    list2.sort()print("list after sort : ", list2)

    The output produced is as shown below −

    list before sort [10, 16, 9, 24, 5]
    list after sort :  [5, 9, 10, 16, 24]
    

    Sorting Lists Using sorted() Method

    The sorted() function in Python is a built-in function used to sort the elements of an iterable (such as a list, tuple, or string) and returns a new sorted list, leaving the original iterable unchanged.

    Syntax

    The syntax for using the sorted() method is as follows −

    sorted(iterable, key=None, reverse=False)

    Where,

    • iterable is the iterable (e.g., list, tuple, string) whose elements are to be sorted.
    • key (optional) is a function that defines the sorting criterion. If provided, it is applied to each element of the iterable for sorting. Default is None.
    • reverse (optional) is a boolean value. If True, the iterable will be sorted in descending order. If False (default), the iterable will be sorted in ascending order.

    Example

    In the following example, we are using the sorted() function to sort a list of numbers and retrieve a new sorted list −

    numbers =[3,1,4,1,5,9,2,6,5,3,5]# Sorting in descending order
    sorted_numbers_desc =sorted(numbers, reverse=True)print(sorted_numbers_desc)

    Following is the output of the above code −

    [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
    

    Sorting List Items with Callback Function

    In Python, a callback function refers to a function that is passed as an argument to another function and is invoked or called within that function

    We can sort list items with a callback function by using the sorted() function or sort() function in Python. Both of these functions allows us to specify a custom sorting criterion using the “key” parameter, which accepts a callback function. This callback function defines how the elements should be compared and sorted.

    Example Using str.lower() as key Parameter

    The str.lower() method in Python is used to convert all the characters in a string to lowercase. It returns a new string with all alphabetic characters converted to lowercase while leaving non-alphabetic characters unchanged.

    In this example, we are passing the str.lower() method as an argument to the “key” parameter within the sort() function −

    list1 =['Physics','biology','Biomechanics','psychology']print("list before sort", list1)
    list1.sort(key=str.lower)print("list after sort : ", list1)

    It will produce the following output −

    list before sort ['Physics', 'biology', 'Biomechanics', 'psychology']
    list after sort : ['biology', 'Biomechanics', 'Physics', 'psychology']
    

    Example Using user-defined Function as key Parameter

    We can also use a user-defined function as the key parameter in sort() method.

    In this example, the myfunction() uses % operator to return the remainder, based on which the sorting is performed −

    defmyfunction(x):return x%10
    list1 =[17,23,46,51,90]print("list before sort", list1)
    list1.sort(key=myfunction)print("list after sort : ", list1)

    It will produce the following output −

    list before sort [17, 23, 46, 51, 90]
    list after sort: [90, 51, 23, 46, 17]
  • List Comprehension

    List Comprehension in Python

    list comprehension is a concise way to create lists. It is similar to set builder notation in mathematics. It is used to define a list based on an existing iterable object, such as a list, tuple, or string, and apply an expression to each element in the iterable.

    Syntax of Python List Comprehension

    The basic syntax of list comprehension is −

    new_list =[expression for item in iterable if condition]

    Where,

    • expression is the operation or transformation to apply to each item in the iterable.
    • item is the variable representing each element in the iterable.
    • iterable is the sequence of elements to iterate over.
    • condition (optional) is an expression that filters elements based on a specified condition.

    Example of Python List Comprehension

    Suppose we want to convert all the letters in the string “hello world” to their upper-case form. Using list comprehension, we iterate through each character, check if it is a letter, and if so, convert it to uppercase, resulting in a list of uppercase letters −

    string ="hello world"
    uppercase_letters =[char.upper()for char in string if char.isalpha()]print(uppercase_letters)

    The result obtained is displayed as follows −

    ['H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D']
    

    List Comprehensions and Lambda

    In Python, lambda is a keyword used to create anonymous functions. An anonymous function is a function defined without a name. These functions are created using the lambda keyword followed by a comma-separated list of arguments, followed by a colon :, and then the expression to be evaluated.

    We can use list comprehension with lambda by applying the lambda function to each element of an iterable within the comprehension, generating a new list.

    Example

    In the following example, we are using list comprehension with a lambda function to double each element in a given list “original_list”. We iterate over each element in the “original_list” and apply the lambda function to double it −

    Open Compiler

    original_list =[1,2,3,4,5]
    doubled_list =[(lambda x: x *2)(x)for x in original_list]print(doubled_list)

    Following is the output of the above code −

    [2, 4, 6, 8, 10]
    

    Nested Loops in Python List Comprehension

    A nested loop in Python is a loop inside another loop, where the inner loop is executed multiple times for each iteration of the outer loop.

    We can use nested loops in list comprehension by placing one loop inside another, allowing for concise creation of lists from multiple iterations.

    Example

    In this example, all combinations of items from two lists in the form of a tuple are added in a third list object −

    Open Compiler

    list1=[1,2,3]
    list2=[4,5,6]
    CombLst=[(x,y)for x in list1 for y in list2]print(CombLst)

    It will produce the following output −

    [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]
    

    Conditionals in Python List Comprehension

    Conditionals in Python refer to the use of statements like “if”, “elif”, and “else” to control the flow of a code based on certain conditions. They allow you to execute different blocks of code depending on whether a condition evaluates to “True” or “False”.

    We can use conditionals in list comprehension by including them after the iterable and before the loop, which filters elements from the iterable based on the specified condition while generating the list.

    Example

    The following example uses conditionals within a list comprehension to generate a list of even numbers from 1 to 20 −

    Open Compiler

    list1=[x for x inrange(1,21)if x%2==0]print(list1)

    We get the output as follows −

    [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
    

    List Comprehensions vs For Loop

    List comprehensions and for loops are both used for iteration, but they differ in terms of syntax and usage.

    List comprehensions are like shortcuts for creating lists in Python. They let you generate a new list by applying an operation to each item in an existing list.

    For loop, on the other hand, is a control flow statement used to iterate over elements of an iterable one by one, executing a block of code for each element.

    List comprehensions are often preferred for simpler operations, while for loops offer more flexibility for complex tasks.

    Example Using For Loop

    Suppose we want to separate each letter in a string and put all non-vowel letters in a list object. We can do it by a for loop as shown below −

    chars=[]for ch in'TutorialsPoint':if ch notin'aeiou':
    
      chars.append(ch)print(chars)</pre>

    The chars list object is displayed as follows −

    ['T', 't', 'r', 'l', 's', 'P', 'n', 't']
    

    Example Using List Comprehension

    We can easily get the same result by a list comprehension technique. A general usage of list comprehension is as follows −

    listObj =[x for x in iterable]

    Applying this, chars list can be constructed by the following statement −

    chars =[ char for char in'TutorialsPoint'if char notin'aeiou']print(chars)

    The chars list will be displayed as before −

    ['T', 't', 'r', 'l', 's', 'P', 'n', 't']
    

    Example

    The following example uses list comprehension to build a list of squares of numbers between 1 to 10 −

    squares =[x*x for x inrange(1,11)]print(squares)

    The squares list object is −

    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
    

    Advantages of List Comprehension

    Following are the advantages of using list comprehension −

    • Conciseness − List comprehensions are more concise and readable compared to traditional for loops, allowing you to create lists with less code.
    • Efficiency − List comprehensions are generally faster and more efficient than for loops because they are optimized internally by Python's interpreter.
    • Clarity − List comprehensions result in clearer and more expressive code, making it easier to understand the purpose and logic of the operation being performed.
    • Reduced Chance of Errors − Since list comprehensions are more compact, there is less chance of errors compared to traditional for loops, reducing the likelihood of bugs in your code.
  • Loop Lists

    Loop Through List Items

    Looping through list items in Python refers to iterating over each element within a list. We do so to perform the desired operations on each item. These operations include list modification, conditional operations, string manipulation, data analysis, etc.

    Python provides various methods for looping through list items, with the most common being the for loop. We can also use the while loop to iterate through list items, although it requires additional handling of the loop control variable explicitly i.e. an index.

    Loop Through List Items with For Loop

    A for loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, string, or range) or any other iterable object. It allows you to execute a block of code repeatedly for each item in the sequence.

    In a for loop, you can access each item in a sequence using a variable, allowing you to perform operations or logic based on that item’s value. We can loop through list items using for loop by iterating over each item in the list.

    Syntax

    Following is the basic syntax to loop through items in a list using a for loop in Python −

    for item inlist:# Code block to execute

    Example

    In the following example, we are using a for loop to iterate through each element in the list “lst” and retrieving each element followed by a space on the same line −

    Open Compiler

    lst =[25,12,10,-21,10,100]for num in lst:print(num, end =' ')

    Output

    Following is the output of the above code −

    25 12 10 -21 10 100
    

    Loop Through List Items with While Loop

    A while loop in Python is used to repeatedly execute a block of code as long as a specified condition evaluates to “True”.

    We can loop through list items using while loop by initializing an index variable, then iterating through the list using the index variable and incrementing it until reaching the end of the list.

    An index variable is used within a loop to keep track of the current position or index in a sequence, such as a list or array. It is generally initialized before the loop and updated within the loop to iterate over the sequence.

    Syntax

    Following is the basic syntax for looping through items in a list using a while loop in Python −

    while condition:# Code block to execute

    Example

    In the below example, we iterate through each item in the list “my_list” using a while loop. We use an index variable “index” to access each item sequentially, incrementing it after each iteration to move to the next item −

    my_list =[1,2,3,4,5]
    index =0while index <len(my_list):print(my_list[index])
       index +=1

    Output

    Output of the above code is as follows −

    1
    2
    3
    4
    5
    

    Loop Through List Items with Index

    An index is a numeric value representing the position of an element within a sequence, such as a list, starting from 0 for the first element.

    We can loop through list items using index by iterating over a range of indices corresponding to the length of the list and accessing each element using the index within the loop.

    Example

    This example initializes a list “lst” with integers and creates a range of indices corresponding to the length of the list. Then, it iterates over each index in the range and prints the value at that index in the list “lst” −

    lst =[25,12,10,-21,10,100]
    indices =range(len(lst))for i in indices:print("lst[{}]: ".format(i), lst[i])

    Output

    We get the output as shown below −

    lst[0]: 25
    lst[1]: 12
    lst[2]: 10
    lst[3]: -21
    lst[4]: 10
    lst[5]: 100
    

    Iterate using List Comprehension

    A list comprehension in Python is a concise way to create lists by applying an expression to each element of an iterable. These expressions can be arithmetic operations, function calls, conditional expressions etc.

    We can iterate using list comprehension by specifying the expression and the iterable (like a list, tuple, dictionary, string, or range). Following is the syntax −

    [expression for item in iterable]

    This applies the expression to each item in the iterable and creates a list of results.

    Example

    In this example, we use list comprehension to iterate through each number in a list of numbers, square each one, and store the squared result in the new list “squared_numbers” −

    numbers =[1,2,3,4,5]
    squared_numbers =[num **2for num in numbers]print(squared_numbers)

    Output

    We get the output as shown below −

    [1, 4, 9, 16, 25]
    

    Iterate using the enumerate() Function

    The enumerate() function in Python is used to iterate over an iterable object while also providing the index of each element.

    We can iterate using the enumerate() function by applying it to the iterable. Following is the syntax −

    for index, item inenumerate(iterable):

    This provides both the index and item of each element in the iterable during iteration

    Example

    In the following example, we are using the enumerate() function to iterate through a list “fruits” and retrieve each fruit along with its corresponding index −

    fruits =["apple","banana","cherry"]for index, fruit inenumerate(fruits):print(index, fruit)

    Output

    We get the output as shown below −

    0 apple
    1 banana
    2 cherry
  •  Remove List Items

    Removing List Items

    Removing list items in Python implies deleting elements from an existing list. Lists are ordered collections of items, and sometimes you need to remove certain elements from them based on specific criteria or indices. When we remove list items, we are reducing the size of the list or eliminating specific elements.

    We can remove list items in Python using various methods such as remove()pop() and clear(). Additionally, we can use the del statement to remove items at a specific index. Let us explore through all these methods in this tutorial.

    Remove List Item Using remove() Method

    The remove() method in Python is used to remove the first occurrence of a specified item from a list.

    We can remove list items using the remove() method by specifying the value we want to remove within the parentheses, like my_list.remove(value), which deletes the first occurrence of value from my_list.

    Example

    In the following example, we are deleting the element “Physics” from the list “list1” using the remove() method −

    list1 =["Rohan","Physics",21,69.75]print("Original list: ", list1)
    
    list1.remove("Physics")print("List after removing: ", list1)

    It will produce the following output −

    Original list: ['Rohan', 'Physics', 21, 69.75]
    List after removing: ['Rohan', 21, 69.75]
    

    Remove List Item Using pop() Method

    The pop() method in Python is used to removes and returns the last element from a list if no index is specified, or removes and returns the element at a specified index, altering the original list.

    We can remove list items using the pop() method by calling it without any arguments my_list.pop(), which removes and returns the last item from my_list, or by providing the index of the item we want to remove my_list.pop(index), which removes and returns the item at that index.

    Example

    The following example shows how you can use the pop() method to remove list items −

    list2 =[25.50,True,-55,1+2j]print("Original list: ", list2)
    list2.pop(2)print("List after popping: ", list2)

    We get the output as shown below −

    Original list: [25.5, True, -55, (1+2j)]
    List after popping: [25.5, True, (1+2j)]
    

    Remove List Item Using clear() Method

    The clear() method in Python is used to remove all elements from a list, leaving it empty.

    We can remove all list items using the clear() method by calling it on the list object like my_list.clear(), which empties my_list, leaving it with no elements.

    Example

    In this example, we are using the clear() method to remove all elements from the list “my_list” −

    my_list =[1,2,3,4,5]# Clearing the list
    my_list.clear()print("Cleared list:", my_list)

    Output of the above code is as follows −

    Cleared list: []
    

    Remove List Item Using del Keyword

    The del keyword in Python is used to delete element either at a specific index or a slice of indices from memory.

    We can remove list items using the del keyword by specifying the index or slice of the items we want to delete, like del my_list[index] to delete a single item or del my_list[start:stop] to delete a range of items.

    Example

    In the below example, we are using the “del” keyword to delete an element at the index “2” from the list “list1” −

    list1 =["a","b","c","d"]print("Original list: ", list1)del list1[2]print("List after deleting: ", list1)

    The result produced is as follows −

    Original list: ['a', 'b', 'c', 'd']
    List after deleting: ['a', 'b', 'd']
    

    Example

    In here, we are deleting a series of consecutive items from a list with the slicing operator −

    list2 =[25.50,True,-55,1+2j]print("List before deleting: ", list2)del list2[0:2]print("List after deleting: ", list2)

    It will produce the following output −

    List before deleting: [25.5, True, -55, (1+2j)]
    List after deleting: [-55, (1+2j)]
  • Add List Items

    Add List Items

    Adding list items in Python implies inserting new elements into an existing list. Lists are mutable, meaning they can be modified after creation, allowing for the addition, removal, or modification of their elements.

    Adding items in a list typically refers to appending new elements to the end of the list, inserting them at specific positions within the list, or extending the list with elements from another iterable object.

    We can add list items in Python using various methods such as append(), extend() and insert(). Let us explore through all these methods in this tutorial.

    Adding List Items Using append() Method

    The append() method in Python is used to add a single element to the end of a list.

    We can add list items using the append() method by specifying the element we want to add within the parentheses, like my_list.append(new_item), which adds new_item to the end of my_list.

    Example

    In the following example, we are adding an element “e” to the end of the list “list1” using the append() method −

    list1 =["a","b","c","d"]print("Original list: ", list1)
    list1.append('e')print("List after appending: ", list1)

    Output

    Following is the output of the above code −

    Original list: ['a', 'b', 'c', 'd']
    List after appending: ['a', 'b', 'c', 'd', 'e']
    

    Adding List Items Using insert() Method

    The insert() method in Python is used to add an element at a specified index (position) within a list, shifting existing elements to accommodate the new one.

    We can add list items using the insert() method by specifying the index position where we want to insert the new item and the item itself within the parentheses, like my_list.insert(index, new_item).

    Example

    In this example, we have an original list containing various items. We use the insert() method to add new elements to the list at specific positions −

    list1 =["Rohan","Physics",21,69.75]
    
    list1.insert(2,'Chemistry')print("List after appending: ", list1)
    
    list1.insert(-1,'Pass')print("List after appending: ", list1)

    After appending ‘Chemistry’ to the list, we get the following output −

    List after appending: ['Rohan', 'Physics', 'Chemistry', 21, 69.75]
    

    Then, by inserting ‘Pass’ at the index “-1”, which originally referred to 69.75, we get −

    List after appending: ['Rohan', 'Physics', 'Chemistry', 21, 'Pass', 69.75]
    

    We can see that “Pass” is not inserted at the updated index “-1”, but the previous index “-1”. This behavior is because when appending or inserting items into a list, Python does not dynamically update negative index positions.

    Adding List Items Using extend() Method

    The extend() method in Python is used to add multiple elements from an iterable (such as another list) to the end of a list.

    We can add list items using the extend() method by passing another iterable containing the elements we want to add, like my_list.extend(iterable), which appends each element from the iterable to the end of my_list.

    Example

    In the below example, we are using the extend() method to add the elements from “another_list” to the end of “list1” −

    # Original list
    list1 =[1,2,3]# Another list to extend with
    another_list =[4,5,6]
    
    list1.extend(another_list)print("Extended list:", list1)

    Output

    Output of the above code is as follows −

    Extended list: [1, 2, 3, 4, 5, 6]
  •  Change List Items

    Change List Items

    List is a mutable data type in Python. It means, the contents of list can be modified in place, after the object is stored in the memory. You can assign a new value at a given index position in the list

    Syntax

    list1[i] = newvalue
    

    Example

    In the following code, we change the value at index 2 of the given list.

    list3 =[1,2,3,4,5]print("Original list ", list3)
    list3[2]=10print("List after changing value at index 2: ", list3)

    It will produce the following output −

    Original list [1, 2, 3, 4, 5]
    List after changing value at index 2: [1, 2, 10, 4, 5]

    Change Consecutive List Items

    You can replace more consecutive items in a list with another sublist.

    Example

    In the following code, items at index 1 and 2 are replaced by items in another sublist.

    list1 =["a","b","c","d"]print("Original list: ", list1)
    
    list2 =['Y','Z']
    list1[1:3]= list2
    
    print("List after changing with sublist: ", list1)

    It will produce the following output −

    Original list: ['a', 'b', 'c', 'd']
    List after changing with sublist: ['a', 'Y', 'Z', 'd']
    

    Change a Range of List Items

    If the source sublist has more items than the slice to be replaced, the extra items in the source will be inserted. Take a look at the following code −

    Example

    list1 =["a","b","c","d"]print("Original list: ", list1)
    list2 =['X','Y','Z']
    list1[1:3]= list2
    print("List after changing with sublist: ", list1)

    It will produce the following output −

    Original list: ['a', 'b', 'c', 'd']
    List after changing with sublist: ['a', 'X', 'Y', 'Z', 'd']
    

    Example

    If the sublist with which a slice of original list is to be replaced, has lesser items, the items with match will be replaced and rest of the items in original list will be removed.

    In the following code, we try to replace “b” and “c” with “Z” (one less item than items to be replaced). It results in Z replacing b and c removed.

    list1 =["a","b","c","d"]print("Original list: ", list1)
    list2 =['Z']
    list1[1:3]= list2
    print("List after changing with sublist: ", list1)

    It will produce the following output −

    Original list: ['a', 'b', 'c', 'd']
    List after changing with sublist: ['a', 'Z', 'd']