Author: Saim Khalid

  •  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']
    
  • Access List Items

    Access List Items

    In Python, a list is a sequence of elements or objects, i.e. an ordered collection of objects. Similar to arrays, each element in a list corresponds to an index.

    To access the values within a list, we need to use the square brackets “[]” notation and, specify the index of the elements we want to retrieve.

    The index starts from 0 for the first element and increments by one for each subsequent element. Index of the last item in the list is always “length-1”, where “length” represents the total number of items in the list.

    In addition to this, Python provides various other ways to access list items such as slicing, negative indexing, extracting a sublist from a list etc. Let us go through this one-by-one −

    Accessing List Items with Indexing

    As discussed above to access the items in a list using indexing, just specify the index of the element with in the square brackets (“[]”) as shown below −

    mylist[4]

    Example

    Following is the basic example to access list items −

    list1 =["Rohan","Physics",21,69.75]
    list2 =[1,2,3,4,5]print("Item at 0th index in list1: ", list1[0])print("Item at index 2 in list2: ", list2[2])

    It will produce the following output −

    Item at 0th index in list1: Rohan
    Item at index 2 in list2: 3
    

    Access List Items with Negative Indexing

    Negative indexing in Python is used to access elements from the end of a list, with -1 referring to the last element, -2 to the second last, and so on.

    We can also access list items with negative indexing by using negative integers to represent positions from the end of the list.

    Example

    In the following example, we are accessing list items with negative indexing −

    list1 =["a","b","c","d"]
    list2 =[25.50,True,-55,1+2j]print("Item at 0th index in list1: ", list1[-1])print("Item at index 2 in list2: ", list2[-3])

    We get the output as shown below −

    Item at 0th index in list1: d
    Item at index 2 in list2: True
    

    Access List Items with Slice Operator

    The slice operator in Python is used to fetch one or more items from the list. We can access list items with the slice operator by specifying the range of indices we want to extract. It uses the following syntax −

    [start:stop]

    Where,

    • start is the starting index (inclusive).
    • stop is the ending index (exclusive).

    If we does not provide any indices, the slice operator defaults to starting from index 0 and stopping at the last item in the list.

    Example

    In the following example, we are retrieving sublist from index 1 to last in “list1” and index 0 to 1 in “list2”, and retrieving all elements in “list3” −

    list1 =["a","b","c","d"]
    list2 =[25.50,True,-55,1+2j]
    list3 =["Rohan","Physics",21,69.75]print("Items from index 1 to last in list1: ", list1[1:])print("Items from index 0 to 1 in list2: ", list2[:2])print("Items from index 0 to index last in list3", list3[:])

    Following is the output of the above code −

    Items from index 1 to last in list1:  ['b', 'c', 'd']
    Items from index 0 to 1 in list2:  [25.5, True]
    Items from index 0 to index last in list3 ['Rohan', 'Physics', 21, 69.75]
    

    Access Sub List from a List

    A sublist is a part of a list that consists of a consecutive sequence of elements from the original list. We can access a sublist from a list by using the slice operator with appropriate start and stop indices.

    Example

    In this example, we are fetching sublist from index “1 to 2” in “list1” and index “0 to 1” in “list2” using slice operator −

    list1 =["a","b","c","d"]
    list2 =[25.50,True,-55,1+2j]print("Items from index 1 to 2 in list1: ", list1[1:3])print("Items from index 0 to 1 in list2: ", list2[0:2])

    The output obtained is as follows −

    Items from index 1 to 2 in list1: ['b', 'c']
    Items from index 0 to 1 in list2: [25.5, True]
    
  • Lists

    Python Lists

    List is one of the built-in data types in Python. A Python list is a sequence of comma separated items, enclosed in square brackets [ ]. The items in a Python list need not be of the same data type.

    Following are some examples of Python lists −

    list1 =["Rohan","Physics",21,69.75]
    list2 =[1,2,3,4,5]
    list3 =["a","b","c","d"]
    list4 =[25.50,True,-55,1+2j]

    List is an ordered collection of items. Each item in a list has a unique position index, starting from 0.

    A list in Python is similar to an array in C, C++ or Java. However, the major difference is that in C/C++/Java, the array elements must be of same type. On the other hand, Python lists may have objects of different data types.

    A Python list is mutable. Any item from the list can be accessed using its index, and can be modified. One or more objects from the list can be removed or added. A list may have same item at more than one index positions.

    Accessing Values in Lists

    To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −

    list1 =['physics','chemistry',1997,2000];
    list2 =[1,2,3,4,5,6,7];print("list1[0]: ", list1[0])print("list2[1:5]: ", list2[1:5])

    When the above code is executed, it produces the following result −

    list1[0]:  physics
    list2[1:5]:  [2, 3, 4, 5]
    

    Updating Lists

    You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. For example −

    list=['physics','chemistry',1997,2000];print("Value available at index 2 : ")print(list[2])list[2]=2001;print("New value available at index 2 : ")print(list[2])

    When the above code is executed, it produces the following result −

    Value available at index 2 :
    1997
    New value available at index 2 :
    2001
    

    Delete List Elements

    To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. For example −

    list1 =['physics','chemistry',1997,2000];print(list1)del list1[2];print("After deleting value at index 2 : ")print(list1)

    When the above code is executed, it produces following result −

    ['physics', 'chemistry', 1997, 2000]
    After deleting value at index 2 :
    ['physics', 'chemistry', 2000]
    

    Note − remove() method is discussed in subsequent section.

    Python List Operations

    In Python, List is a sequence. Hence, we can concatenate two lists with “+” operator and concatenate multiple copies of a list with “*” operator. The membership operators “in” and “not in” work with list object.

    Python ExpressionResultsDescription
    [1, 2, 3] + [4, 5, 6][1, 2, 3, 4, 5, 6]Concatenation
    [‘Hi!’] * 4[‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’]Repetition
    3 in [1, 2, 3]TrueMembership

    Indexing, Slicing, and Matrixes

    Because lists are sequences, indexing and slicing work the same way for lists as they do for strings.

    Assuming following input −

    L = ['spam', 'Spam', 'SPAM!']
    
    Python ExpressionResultsDescription
    L[2]SPAM!Offsets start at zero
    L[-2]SpamNegative: count from the right
    L[1:][‘Spam’, ‘SPAM!’]Slicing fetches sections

    Python List Methods

    Python includes following list methods −

    Sr.No.Methods with Description
    1list.append(obj)Appends object obj to list.
    2list.clear()Clears the contents of list.
    3list.copy()Returns a copy of the list object.
    4list.count(obj)Returns count of how many times obj occurs in list
    5list.extend(seq)Appends the contents of seq to list
    6list.index(obj)Returns the lowest index in list that obj appears
    7list.insert(index, obj)Inserts object obj into list at offset index
    8list.pop(obj=list[-1])Removes and returns last object or obj from list
    9list.remove(obj)Removes object obj from list
    10list.reverse()Reverses objects of list in place
    11list.sort([func])Sorts objects of list, use compare func if given

    Built-in Functions with Lists

    Following are the built-in functions we can use with lists −

    Sr.No.Function with Description
    1cmp(list1, list2)Compares elements of both lists.
    2len(list)Gives the total length of the list.
    3max(list)Returns item from the list with max value.
    4min(list)Returns item from the list with min value.
    5list(seq)Converts a tuple into list.
  • String Exercises


    Example 1

    Python program to find number of vowels in a given string.

    mystr ="All animals are equal. Some are more equal"
    vowels ="aeiou"
    count=0for x in mystr:if x.lower()in vowels: count+=1print("Number of Vowels:", count)

    It will produce the following output −

    Number of Vowels: 18
    

    Example 2

    Python program to convert a string with binary digits to integer.

    mystr ='10101'defstrtoint(mystr):for x in mystr:if x notin'01':return"Error. String with non-binary characters"
       num =int(mystr,2)return num
    print("binary:{} integer: {}".format(mystr,strtoint(mystr)))

    It will produce the following output −

    binary:10101 integer: 21
    

    Change mystr to ’10, 101′

    binary:10,101 integer: Error. String with non-binary characters
    

    Example 3

    Python program to drop all digits from a string.

    digits =[str(x)for x inrange(10)]
    mystr ='He12llo, Py00th55on!'
    chars =[]for x in mystr:if x notin digits:
    
      chars.append(x)
    newstr =''.join(chars)print(newstr)

    It will produce the following output −

    Hello, Python!
    

    Exercise Programs

    • Python program to sort the characters in a string
    • Python program to remove duplicate characters from a string
    • Python program to list unique characters with their count in a string
    • Python program to find number of words in a string
    • Python program to remove all non-alphabetic characters from a string
  •  String Methods

    Python’s built-in str class defines different methods. They help in manipulating strings. Since string is an immutable object, these methods return a copy of the original string, performing the respective processing on it. The string methods can be classified in following categories −

    Case Conversion Methods

    This category of built-in methods of Python’s str class deal with the conversion of alphabet characters in the string object. Following methods fall in this category −

    Sr.No.Method & Description
    1capitalize()Capitalizes first letter of string
    2casefold()Converts all uppercase letters in string to lowercase. Similar to lower(), but works on UNICODE characters alos
    3lower()Converts all uppercase letters in string to lowercase.
    4swapcase()Inverts case for all letters in string.
    5title()Returns “titlecased” version of string, that is, all words begin with uppercase and the rest are lowercase.
    6upper()Converts lowercase letters in string to uppercase.

    Alignment Methods

    Following methods in the str class control the alignment of characters within the string object.

    Sr.No.Methods & Description
    1center(width, fillchar)Returns a string padded with fillchar with the original string centered to a total of width columns.
    2ljust(width[, fillchar])Returns a space-padded string with the original string left-justified to a total of width columns.
    3rjust(width,[, fillchar])Returns a space-padded string with the original string right-justified to a total of width columns.
    4expandtabs(tabsize = 8)Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided.
    5zfill (width)Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero).

    Split and Join Methods

    Python has the following methods to perform split and join operations −

    Sr.No.Method & Description
    1lstrip()Removes all leading whitespace in string.
    2rstrip()Removes all trailing whitespace of string.
    3strip()Performs both lstrip() and rstrip() on string
    4rsplit()Splits the string from the end and returns a list of substrings
    5split()Splits string according to delimiter (space if not provided) and returns list of substrings.
    6splitlines()Splits string at NEWLINEs and returns a list of each line with NEWLINEs removed.
    7partition()Splits the string in three string tuple at the first occurrence of separator
    8rpartition()Splits the string in three string tuple at the ladt occurrence of separator
    9join()Concatenates the string representations of elements in sequence into a string, with separator string.
    10removeprefix()Returns a string after removing the prefix string
    11removesuffix()Returns a string after removing the suffix string

    Boolean String Methods

    Following methods in str class return True or False.

    Sr.No.Methods & Description
    1isalnum()Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.
    2isalpha()Returns true if string has at least 1 character and all characters are alphabetic and false otherwise.
    3isdigit()Returns true if the string contains only digits and false otherwise.
    4islower()Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.
    5isnumeric()Returns true if a unicode string contains only numeric characters and false otherwise.
    6isspace()Returns true if string contains only whitespace characters and false otherwise.
    7istitle()Returns true if string is properly “titlecased” and false otherwise.
    8isupper()Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.
    9isascii()Returns True is all the characters in the string are from the ASCII character set
    10isdecimal()Checks if all the characters are decimal characters
    11isidentifier()Checks whether the string is a valid Python identifier
    12isprintable()Checks whether all the characters in the string are printable

    Find and Replace Methods

    Following are the Find and Replace methods in Python −

    Sr.No.Method & Description
    1count(sub, beg ,end)Counts how many times sub occurs in string or in a substring of string if starting index beg and ending index end are given.
    2find(sub, beg, end)Determine if sub occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise.
    3index(sub, beg, end)Same as find(), but raises an exception if str not found.
    4replace(old, new [, max])Replaces all occurrences of old in string with new or at most max occurrences if max given.
    5rfind(sub, beg, end)Same as find(), but search backwards in string.
    6rindex( sub, beg, end)Same as index(), but search backwards in string.
    7startswith(sub, beg, end)Determines if string or a substring of string (if starting index beg and ending index end are given) starts with substring sub; returns true if so and false otherwise.
    8endswith(suffix, beg, end)Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise.

    Translation Methods

    Following are the Translation methods of the string −

    Sr.No.Method & Description
    1maketrans()Returns a translation table to be used in translate function.
    2translate(table, deletechars=””)Translates string according to translation table str(256 chars), removing those in the del string.