Author name: Vikram Chiluka

Python Dictionary: Pop() Function and Examples

Dictionaries are the implementation by Python of a data structure associative array. A dictionary is a collection of pairs of key values. A key pair and its associated value represent each key pair.

The list of key value pairs in curly braces that is separated by comma defines a dictionary. Column ‘:’ separates the value of each key.

A dictionary cannot be sorted only to get a representation of the sorted dictionary. Inherently, dictionaries are orderless, but not other types, including lists and tuples. Therefore, you need an ordered data type, which is a list—probably a list of tuples.

Pop() was defined in the Python language for almost all containers, including list, set, and so on. This article will demonstrate the pop() method provided by Python dictionaries. This method is useful for programmers who frequently use the dictionary.

Pop Function in Python Dictionary with Examples

1)pop() function

Syntax:

dictionary.pop(key,default)

Parameters:

key: The key for which the key-value pair must be returned and removed.
Default value :If the specified key is not present, the default value is returned.

Return:

If key is present, returns the value associated with the deleted key-value pair.
If no key is specified, the default value is used.
If the key is not present and the default value is not specified, a KeyError is returned.

2)Removing a key-value pair from dictionary using pop()

Assume we have a dictionary with keys of strings and values of integers. Now we want to remove an entry from the dictionary with the key ‘this’. We can implement this as below.

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# given key which should be removed
givenkey = 'this'
# printing the dictionary before modification
print("Before Modification", dictionary)
# removing 'this' key from dictionary
# storing its value in value function
keyvalue = dictionary.pop(givenkey)
# printing the value
print("Value of key :", keyvalue)
# printing the dictionary after modification
print("After Modification", dictionary)

Output:

Before Modification {'this': 200, 'is': 100, 'BTechGeeks': 300}
Value of key : 200
After Modification {'is': 100, 'BTechGeeks': 300}

3)Removing the key which doesn’t exist in given dictionary(with default value)

If we attempt to remove a key from the dictionary that does not exist. The default value will then be returned by the pop() function.

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# given key which should be removed
givenkey = 'hello'
# printing the dictionary before modification
print("Before Modification", dictionary)
# removing 'this' key from dictionary
# storing its value in value function
keyvalue = dictionary.pop(givenkey, 500)
# printing the value
print("Value of key :", keyvalue)
# printing the dictionary after modification
print("After Modification", dictionary)

Output:

Before Modification {'this': 200, 'is': 100, 'BTechGeeks': 300}
Value of key : 500
After Modification {'this': 200, 'is': 100, 'BTechGeeks': 300}

4)Removing the key which doesn’t exist in given dictionary(without default value)

When we use the pop() function, we try to remove a key from the dictionary that does not exist, and we do not pass the default value. The pop() function will then throw a KeyError.

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# given key which should be removed
givenkey = 'hello'
# printing the dictionary before modification
print("Before Modification", dictionary)
# removing 'this' key from dictionary
# storing its value in value function
keyvalue = dictionary.pop(givenkey)
# printing the value
print("Value of key :", keyvalue)
# printing the dictionary after modification
print("After Modification", dictionary)

Output:

Traceback (most recent call last):
  File "/home/bbdc799e66bc794f9534237294f5b64c.py", line 9, in <module>
    keyvalue = dictionary.pop(givenkey)
KeyError: 'hello'

Related Programs:

Python Dictionary: Pop() Function and Examples Read More »

Python: Iterate Over Dictionary with Index

Dictionaries are the implementation by Python of a knowledge structure associative array. A dictionary is a collection of pairs of key values. A key pair and its associated value represent each key pair.
The list of key value pairs in curly braces that’s separated by comma defines a dictionary. Column ‘:’ separates the value of each key.
A dictionary can’t be sorted only to urge a representation of the sorted dictionary. Inherently, dictionaries are orderless, but not other types, including lists and tuples. Therefore, you would like an ordered data type, which may be a list—probably an inventory of tuples.

Examples:

Input :

dictionary = {'This': 100, 'is':200, 'BTechGeeks':300}

Output:

index = 0  ; key = this  ; Value = 200
index = 1  ; key = is  ; Value = 100
index = 2  ; key = BTechGeeks  ; Value = 300

Traverse the Dictionary with Index

1)Enumerate() function:

When working with iterators, we frequently encounter the need to keep track of the number of iterations. Python makes it easier for programmers by providing a built-in function enumerate() for this purpose.
Enumerate() adds a counter to an iterable and returns it as an enumerate object. This enumerate object can then be utilized in for loops directly or converted into an inventory of tuples using the list() method.

Syntax:

enumerate(iterable, start=0)

Parameters:

iterable:  an iterator, a sequence, or objects that support iteration

start :   the index value from which the counter will be started; the default value is 0.

Return:

The method enumerate() adds a counter to an iterable and returns it. The object returned is an enumerate object.

2)Traverse over all key-value pairs of given dictionary by index

We can traverse over the dictionary by passing given dictionary as parameter in enumerate() function

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# Traverse all key-value pairs of given dictionary by index
for i, key in enumerate(dictionary):
    print('index =', i, ' ; key =', key, ' ; Value =', dictionary[key])

Output:

index = 0  ; key = this  ; Value = 200
index = 1  ; key = is  ; Value = 100
index = 2  ; key = BTechGeeks  ; Value = 300

3)Traverse over all keys of given dictionary by index

The dictionary class’s keys() function returns an iterable sequence of all the dictionary’s keys. We can pass that to the enumerate() function, which will return keys as well as index position.

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# Traverse all keys of given dictionary by index
for i, key in enumerate(dictionary.keys()):
    print('index =', i, ' ; key =', key)

Output:

index = 0  ; key = this
index = 1  ; key = is
index = 2  ; key = BTechGeeks

4)Traverse over all values of given dictionary by index

The dictionary class’s values() function returns an iterable sequence of all the dictionary’s values. We can pass that to the enumerate() function, which will return values as well as index position.

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# Traverse all values of given dictionary by index
for i, value in enumerate(dictionary.values()):
    print('index =', i, ' ; value =', value)

Output:

index = 0  ; value = 200
index = 1  ; value = 100
index = 2  ; value = 300

Related Programs:

Python: Iterate Over Dictionary with Index Read More »

Python : Check if a List Contains all the Elements of Another List

In Python, the list datatype is that the most versatile, and it are often written as an inventory of comma-separated values (items) enclosed in square brackets.

Given two lists, the task is to check whether the second list has all the elements of first list.

Examples:

Input:

givenlist1 = ['Hello' , 'this', 'is', 'Btech', 'Geeks']
givenlist2 = ['Btech','Geeks']
Output:
givenlist2 has all of the  givenlist1 elements

Input:

givenlist1 = ['Hello' , 'this', 'is', 'Btech', 'Geeks']
givenlist2 = ['Btech','Geeks','pink']
Output:
givenlist2 doesn't have all of the  givenlist1 elements

Determine whether  a list is included inside another list

There are several ways to check if a list is contained in another list some of them are:

Method #1:Using any() function

The function any() returns True if any of the items in an iterable are true; otherwise, False. The any() function returns False if the iterable object is empty.

Convert list2 to Iterable and check if any element in Iterable, i.e. list2, exists in list1.

Below is the implementation:

# given two lists
givenlist1 = ['Hello', 'this', 'is', 'Btech', 'Geeks']
givenlist2 = ['Btech', 'Geeks']
# using any()
if(any(element in givenlist1 for element in givenlist2)):
    print("givenlist2 has all of the  givenlist1 elements")
else:
    print("givenlist2 doesn't have all of the  givenlist1 elements")

Output:

givenlist2 has all of the  givenlist1 elements

Method #2:Using all() function

In a single line, the all() function is used to check all the elements of a container. Checks if all elements from one list are present in another list.

Below is the implementation:

# given two lists
givenlist1 = ['Hello', 'this', 'is', 'Btech', 'Geeks']
givenlist2 = ['Btech', 'Geeks']
# using all()
if(all(element in givenlist1 for element in givenlist2)):
    print("givenlist2 has all of the  givenlist1 elements")
else:
    print("givenlist2 doesn't have all of the  givenlist1 elements")

Output:

givenlist2 has all of the  givenlist1 elements

Method #3:Using set.issubset()

The most commonly used and recommended method for searching for a sublist. This function is specifically designed to determine whether one list is a subset of another.

Below is the implementation:

# given two lists
givenlist1 = ['Hello', 'this', 'is', 'Btech', 'Geeks']
givenlist2 = ['Btech', 'Geeks']
# using set.issubset() function
if(set(givenlist2).issubset(set(givenlist1))):
    print("givenlist2 has all of the  givenlist1 elements")
else:
    print("givenlist2 doesn't have all of the  givenlist1 elements")

Output:

givenlist2 has all of the  givenlist1 elements

Related Programs:

Python : Check if a List Contains all the Elements of Another List Read More »

Solved- TypeError: Dict_Values Object does not Support Indexing

Python’s implementation of an associative array data structure is dictionaries. A dictionary is a collection of key-value pairs. Each key pair is represented by a key pair and its associated value.

A dictionary is defined by a list of key-value pairs enclosed in curly braces and separated by commas. Each key’s value is separated by a comma in column ‘:’.

A dictionary cannot be sorted solely for the purpose of obtaining a representation of the sorted dictionary. Dictionaries are orderless by definition, but other types, such as lists and tuples, are not. As a result, you require an ordered data type, which is a list—most likely a list of tuples.

Solution for Dict_values object does not support indexing

We can solve this type error by using lists.

Error: ‘dict_values’ object does not support indexing

The dict.values() function returns a view object, and view objects cannot be indexed. If we try to select elements from it using indexing, we will receive the following error.

TypeError: ‘dict_values’ object does not support indexing

Take a dictionary and fetch all the values of the dictionary and print the first index then we get this error.

Implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# extracting the values
dictvalue = dictionary.values()
# printing the dictionary values
print(dictvalue)
print('now extracting the first index of dictvalue')
# printing the first index of dictvalue
print(dictvalue[0])

Output:

dict_values([200, 100, 300])
now extracting the first index of dictvalue
Traceback (most recent call last):
File "./prog.py", line 9, in <module>
TypeError: 'dict_values' object does not support indexing

Solution for this type error

To avoid this error, we can convert the view object dict values to a list and then index it. For example, we can convert the dict values object to a list object and then select an element from it at any index.

We can convert dictionary values to list easily by using list(given_dictionary_name. values())

In this case, we convert all of the values from the dictionary to a list and then chose the first element from the list, which is the first value from the dictionary’s first key-value pair.

Below is the implementation:

# given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# extracting the values and converting to list
dictvalue = list(dictionary.values())
# printing the dictionary values
print(dictvalue)
print('now extracting the first index of dictvalue')
# printing the first index of dictvalue
print(dictvalue[0])

Output:

[200, 100, 300]
now extracting the first index of dictvalue
200

Related Programs:

Solved- TypeError: Dict_Values Object does not Support Indexing Read More »

Python : How to Add an Element in List ? | append() vs extend()

A collection is an ordered list of values. There could be various types of values. A list is a mutable container. This means that existing ones can be added to, deleted from, or changed.

The Python list represents the mathematical concept of a finite sequence. List values are referred to as list items or list elements. The same value may appear multiple times in a list. Each event is regarded as a distinct element.

Given a list, the task is to add the elements to the givenlist using append and extend methods

Adding element to the list

We can add elements to list by several methods some of them are:

Method #1:Using append()

To add elements to the List, use the built-in append() function. The append() method can only add one element to a list at a time; loops are used to add multiple elements to a list using the append() method. Tuples can be added to the List using the append method because they are immutable. Lists, unlike Sets, can be appended to another list using the append() method.

Below is the implementation:

# given list
givenlist = ['hello', 'this', 'is', 'BtechGeeks']
# adding element to the givenlist using append() function
givenlist.append('Python')
# print the list
print(givenlist)

Output:

['hello', 'this', 'is', 'BtechGeeks', 'Python']

Method #2:Using append() function to add multiple elements

Because a list can contain various types of elements, we can pass another list object as a parameter in append ()

Below is the implementation:

# given list
givenlist = ['hello', 'this', 'is', 'BtechGeeks']
# given elementslist which should be added
elementslist = ['python', 'code']
# adding elementslist to the givenlist using append() function
givenlist.append(elementslist)
# print the list
print(givenlist)

Output:

['hello', 'this', 'is', 'BtechGeeks', ['python', 'code']]

Method #3:Using extend() function

Other than the append() and insert() methods for adding elements, there is extend(), which is used at the end of the list to add multiple elements at once.

Append() and extend() can only add elements at the end of a list.

Below is the implementation:

# given list
givenlist = ['hello', 'this', 'is', 'BtechGeeks']
# given elementslist which should be added
elementslist = ['python', 'code']
# adding elementslist to the givenlist using append() function
givenlist.extend(elementslist)
# print the list
print(givenlist)

Output:

['hello', 'this', 'is', 'BtechGeeks', 'python', 'code']

append() vs extend()

list.append(item) treats the parameter item as an individual object and appends it to the end of the list. Even if the given item is already in another list, it will be added to the end of the list as an individual object.

list.extend(item) treats parameter item as a new list and adds all of the list’s individual elements to the current list.
Related Programs:

Python : How to Add an Element in List ? | append() vs extend() Read More »

Check the First or Last Character of a String in Python

In Python, strings are sequences of bytes that represent Unicode characters. Due to the lack of a character data form in Python, a single character is simply a one-length string. To access the string’s components, use square brackets.

Examples:

Checking the last character:

Input:

string="BTechGeeks" lastcharacter='s'

Output:

Last character of string endswith s

Input:

string="BTechGeeks" lastcharacter='p'

Output:

Last character of string do no not end with p

Checking the first character:

Input:

string = 'BTechGeeks'  firstchar = 'B'

Output:

First character of string start with B

Input:

string = 'BTechGeeks'  firstchar = 'r'

Output:

First character of string do no not start with r

Checking the Last and First Character of the String

There are several ways to check first and last character of the string some of them are:

Checking last Character:

Method #1: Using negative slicing

Select the last element with a negative index to verify the condition on the string’s last character.

Below is the implementation:

# given string
string = 'BTechGeeks'
lastchar = 'p'
# check the last character ends with s
if(string[-1] == lastchar):
    print('Last character of string endswith', lastchar)
else:
    print('Last character of string do no not end with', lastchar)

Output:

Last character of string endswith s

Method #2:Using length of string

To check the condition on a string’s last character, first determine the length of the string. Then, at index size -1, check the content of the character.

Below is the implementation:

string = 'BTechGeeks'
lastchar = 's'
# calculating length of string
length = len(string)
# check the last character ends with s
if(string[length-1] == lastchar):
    print('Last character of string endswith', lastchar)
else:
    print('Last character of string do no not end with', lastchar)

Output:

Last character of string endswith s

Method #3:Using endswith()

If a string ends with the specified suffix, the endswith() method returns True; otherwise, it returns False.

Below is the implementation:

string = 'BTechGeeks'
lastchar = 's'
# calculating length of string
length = len(string)
# check the last character ends with s using endswith()
if(string.endswith(lastchar)):
    print('Last character of string endswith', lastchar)
else:
    print('Last character of string do no not end with', lastchar)

Output:

Last character of string endswith s

Method #4: Checking whether the string’s last character matches any of the given multiple characters

In comparison to the previous solutions, endswith() adds a new function. We may also move a tuple of characters to endswith(), which will check whether the last character of the string matches any of the characters in the specified tuple or not.

Below is the implementation:

# Given string and characters
string = 'BTechGeeks'
lastchars = ('s', 'p', 'e')
# check the first character of the given string
if(string.endswith(lastchars)):
    print('Given string ends with one of the given characters')

Output:

Given string ends with one of the given characters

Checking First Character:

Method #5:Using index 0 to get first character

A string is a set of characters, with indexing starting at 0. To find the first character in a string, select the character at the 0th index.

Below is the implementation:

# Given string and character
string = 'BTechGeeks'
firstchar = 'B'
# check the first character of the given string
if(string[0] == firstchar):
    print('First character of string start with', firstchar)
else:
    print('First character of string do no not start with', firstchar)

Output:

First character of string start with B

Method #6:Using startswith()

Python’s String class has a function called startswith() that takes a character or a tuple of characters and checks whether a string begins with that character or not. Let’s use this to see if our string’s first character is ‘B’

Below is the implementation:

# Given string
string = 'BTechGeeks'
firstchar = 'B'
# check the first character of the given string
if(string.startswith(firstchar)):
    print('First character of string start with', firstchar)
else:
    print('First character of string do no not start with', firstchar)

Output:

First character of string start with B

Method #7:Checking whether the string’s last character matches any of the given multiple characters

startswith () adds a extra function . We may also transfer a character tuple, and it will check if the first character of the string matches any of the characters in the tuple.

Below is the implementation:

# Given string and first char
string = 'BTechGeeks'
firstchars = ('s', 'p', 'B')
# check the first character of the given string
if(string.startswith(firstchars)):
    print('given string starts with one of the given characters')

Output:

given string starts with one of the given characters

Related Programs:

Check the First or Last Character of a String in Python Read More »

Python: Get First Value in a Dictionary

Dictionaries are Python’s implementation of an associative array, which is a data structure. A dictionary is made up of a set of key-value pairs. Each key-value pair corresponds to a key and its corresponding value.

A dictionary is defined by enclosing a comma-separated list of key-value pairs in curly braces { }. Each key is separated from its associated value by a colon ‘ :

Examples:

Input :

dictionary = {'This': 100, 'is':200, 'BTechGeeks':300}

Output:

100

Find the first value in a dictionary

There are several ways to find the first value in a dictionary some of them are:

Method #1:Using item() function

The view object is returned by the items() method. The key-value pairs of the dictionary are stored in the view object as tuples in a list. Any changes made to the dictionary will be reflected in the view object.

The dictionary’s item() function returns a view of all dictionary items in the form of a sequence of all key-value pairs. Choose the first key-value pair and the first value from this sequence.

Below is the implementation:

# Given Dictionary
dictionary = {'this': 100, 'is': 200, 'BTechGeeks': 300}
# converting dictionary items to list
dictlist = list(dictionary.items())
# printing the first value of this list
print(dictlist[0][1])

Output:

100

Method #2:Using list() and values() functions

To complete this task, a combination of the methods listed above can be used. In this, we just convert the entire dictionaries values extracted by values() into a list and just access the first values. There is only one thing you should keep in mind when using this, and that is its complexity. It will first convert the entire dictionary to a list by iterating over each item, after which it will extract the first element. The complexity of this method would be O(n).

Below is the implementation:

# Given Dictionary
dictionary = {'this': 100, 'is': 200, 'BTechGeeks': 300}
# converting dictionary values to list
dictlist = list(dictionary.values())
# printing the first value of this list
print(dictlist[0])

Output:

100

Method #3:Using iter() and next() functions

These functions can also be used to complete this task. In this case, we simply use next() to get the first next value, and the iter() function is used to get the iterable conversion of dictionary items. So, if you only need the first value, this method is more efficient. Its complexity would be O(1).

Below is the implementation:

# Given Dictionary
dictionary = {'this': 100, 'is': 200, 'BTechGeeks': 300}
# Get first value of dictionary using iter
firstval = next(iter(dictionary.items()))[1]
# printing the first value
print(firstval)

Output:

100

Retrieve the first N values from a Python dictionary

Using list() + values() +slicing:

Convert the dictionary values into a list.

Retrieve the first n values of the dictionary using slicing.

Below is the implementation:

# Given Dictionary
dictionary = {'this': 100, 'is': 200, 'BTechGeeks': 300}
# Given n
n = 2
# converting dictionary values to list
dictvalues = list(dictionary.values())
# print all values upto n using slicing
print(*dictvalues[:n])

Output:

100 200

Related Programs:

Python: Get First Value in a Dictionary Read More »

Python: Remove Elements from List by Value

Lists are ordered sequences that can contain a wide range of object types. Members on lists can also be duplicated. Lists in Python are equivalent to arrays in other programming languages. There is, however, one significant difference. Arrays can only have elements of the same data type, whereas Python lists can have items of different data types.

Python Lists have several methods for removing elements from the list.

Examples:

Input:

givenlist=["hello", "this", "is", "Btech", "Geeks" ,"is" ] , value=is

Output:

["hello", "this", "Btech", "Geeks"]

Remove Elements from the List by Values

There are several ways to remove elements from the list by values some of them are:

Method #1:Using remove() function

The remove method removes a list element based on its value rather than its index. When more than one element matches the provided value, the first matching element (the one with the lowest index) is removed. This is useful when you know which element needs to be removed ahead of time and don’t want to waste time looking for its index before removing it.

Let us now use the remove() function to remove the first instance of an element ‘is’.

Below is the implementation:

# Function which removes the element for given value and returns list
def removeValue(givenlist, value):
    # removing the value using remove()
    givenlist.remove(value)
    # return the list
    return givenlist

# Driver code


# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks", "is"]
# given value which is to be removed
value = 'is'
# passing list and value to removeValue function to remove the element
print(removeValue(givenlist, value))

Output:

['hello', 'this', 'Btech', 'Geeks', 'is']

If we use the remove() function to remove an element from a list that does not exist, what happens? In that case, Value Error will be returned.

Method #2: Removing given value using remove() if exist

To avoid the ValueError, we check to see if the value is already in the list and then remove it.

Below is the implementation:

# Function which removes the element for given value and returns list
def removeValue(givenlist, value):
  # checking if value is present in givenlist
    if value in givenlist:
     # removing the value using remove()
        givenlist.remove(value)
    # return the list
    return givenlist

# Driver code


# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks", "is"]
# given value which is to be removed
value = 'is'
# passing list and value to removeValue function to remove the element
print(removeValue(givenlist, value))

Output:

['hello', 'this', 'Btech', 'Geeks', 'is']

Method #3:Removing all occurrences of  given value

As we saw in the previous examples, the remove() function always deletes the first occurrence of the given element from the list. To delete all occurrences of an element, we must use the remove() function in a loop until all occurrences are gone.

So we use while loop to achieve that.

Below is the implementation:

# Function which removes the element for given value and returns list
def removeValue(givenlist, value):
    # using while loop to remove all occurrences of given value
    while(value in givenlist):
        # removing the value using remove()
        givenlist.remove(value)
       # return the list
    return givenlist

# Driver code


# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks", "is"]
# given value which is to be removed
value = 'is'
# passing list and value to removeValue function to remove the element
print(removeValue(givenlist, value))

Output:

['hello', 'this', 'Btech', 'Geeks']

Method #4: Using values, remove all occurrences of multiple elements from a list.

Assume we have a list of numbers and another list of values that we want to remove from the first list. We want to remove all of the elements from list2 from list1.

We’ve created a separate function for this, which takes two different lists as arguments.

  • The first is the givenlist.
  • The elements we want to remove are listed in the second list(valuelist)

It deletes all occurrences from the original list for each element in the second list.

Approach:

  • Traverse the value list
  • Using while loop remove all occurrences of the value from given list.
  • Return given list

Below is the implementation:

# Function which removes the element for given value and returns list
def removeValue(givenlist, valuelist):
    # Traverse the value list
    for value in valuelist:
       # using while loop to remove all occurrences of given value
        while(value in givenlist):
            # removing the value using remove()
            givenlist.remove(value)
           # return the list
    return givenlist

# Driver code


# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks", "is"]
# given value list which is to be removed
valuelist = ['is', 'hello', 'this']
# passing list and valuelist to removeValue function to remove the element
print(removeValue(givenlist, valuelist))

Output:

['Btech', 'Geeks']

Related Programs:

Python: Remove Elements from List by Value Read More »

Python : Sort a List of Numbers in Ascending or Descending Order | list.sort() vs sorted()

A list is used in Python to store the sequence of different types of data. Python lists are mutable, which means that their elements can be changed after they have been created. Python, on the other hand, has six data types that can be used to store sequences, with the first two on the list being the most common and accurate.

A list is a collection of various types of values or objects. The list items are separated by a comma (,), which is enclosed in square brackets [].

Example:

Input:

givenlist = [3, 5, 1, 6, 9, 2, 8, 7]

Output:

Ascending order:

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

Descending order:

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

Sort the given list

In this article, we’ll look at two methods for sorting a list of numbers in ascending and descending order.

Method #1: Using sort() function to sort in ascending order:

It’s a built-in function that takes an iterable and returns a new sorted list from it.
Note:

  •  sort is a list class method that can only be used with lists. It is not a built-in that has been passed an iterable.
  • sort() returns None and modifies the existing values. Let’s look at the effects of both of these code differences.

Let us the sort the list of integers in ascending order

Below is the implementation:

# Driver code
# Given list
givenlist = [3, 5, 1, 6, 9, 2, 8, 7]
# sorting the given list in ascending order
givenlist.sort()
print(givenlist)

Output:

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

Method #2: Using sort() function to sort in descending order:

Using reverse=True gives the list in descending order

Below is the implementation:

# Driver code
# Given list
givenlist = [3, 5, 1, 6, 9, 2, 8, 7]
# sorting the given list in descending order
givenlist.sort(reverse=True)
print(givenlist)

Output:

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

Method #3: Using sorted() function to sort in ascending order

The sorted() function returns a sorted list of the iterable object specified. You can specify whether the order should be ascending or descending. Numbers are sorted numerically, while strings are sorted alphabetically. It is important to note that you cannot sort a list that contains BOTH string and numeric values.

Characteristics of sorted() function:

  • It was not necessary to define the function sorted(). It is a built-in function that is available in a standard Python installation.
  • With no additional arguments or parameters, sorted() orders the values in numbers in ascending order, from smallest to largest.
  • Because sorted() returns sorted results and does not change the original value in place, the original numbers variable remains unchanged.
  • When sorted() is invoked, it returns an ordered list as a result.

Below is the implemenation:

# Driver code
# Given list
givenlist = [3, 5, 1, 6, 9, 2, 8, 7]

# using sorted function to sort the given list in ascending order
newlist = sorted(givenlist)
# printing the newlist
print(newlist)

Output:

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

Method #4: Using sorted() function to sort in descending order:

Using reverse=True gives the list in descending order

Below is the implementation:

# Driver code
# Given list
givenlist = [3, 5, 1, 6, 9, 2, 8, 7]

# using sorted function to sort the given list in descending order using reverse=True
newlist = sorted(givenlist, reverse=True)
# printing the newlist
print(newlist)

Output:

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

 

Related Programs:

Python : Sort a List of Numbers in Ascending or Descending Order | list.sort() vs sorted() Read More »

Python How to Remove Multiple Elements from List

Python : How to Remove Multiple Elements from List ?

In Python, a list is used to store the sequence of different types of data. Python lists are mutable, which means we can change their elements after they’ve been formed. However, Python has six data types that can be used to store sequences, with the list being the most common and accurate.

A list can be described as a set of different types of values or objects. The comma (,) separates the things in the list, which are enclosed in square brackets [].

Remove multiple items from the list

The following is a list of possible python methods to remove multiple elements from the list:

Method #1:Using remove() function while iterating through the list

The remove() method removes the first matching element from the list (which is passed as an argument).

remove() parameters:

  • The remove() method accepts a single argument and removes it from the list.
  • If the element does not exist, a ValueError: list.remove(x): x not in list exception is thrown.

Let us remove all elements which are divisible by 2.

Traverse the list and remove the element if it is divisible by 2.

Below is the implementation:

# function which remove multiple items from the list
def removeMultiple(givenlist):
    # Traverse the list
    for element in list(givenlist):
        # Checking the given condition
        if(element % 2 == 0):
            # remove the element from the given list
            givenlist.remove(element)
    # return the given list
    return(givenlist)


# Driver code
# Given list
givenlist = [1, 2, 3, 4, 5, 6, 7, 8]
# passing the list to removeMultiple function
print(removeMultiple(givenlist))

Output:

[1, 3, 5, 7]

Method #2:Using del keyword and slicing

Another way to delete an element from a list is to use its index in the del statement. It differs from the pop() function in that it does not return the removed element. Unlike the slicing feature, this does not generate a new list.

If we want to remove multiple elements from a list based on an index range, we can use the del keyword.

Suppose we want to delete elements from 2 to 5 indices we can use slicing and del keyword to do that.

It will remove the elements from index1 to index2 – 1 from the list.

Below is the implementation:

# function which remove multiple items from the list
def removeMultiple(givenlist):
    # using del keyword and removing indices from 2 to 5
    # increment the right index with 1 to remove it
    del givenlist[2:6]
    # return the given list
    return(givenlist)


# Driver code
# Given list
givenlist = [1, 2, 3, 4, 5, 6, 7, 8]
# passing the list to removeMultiple function
print(removeMultiple(givenlist))

Output:

[1, 2, 7, 8]

Method #3: Using List Comprehension

Python’s syntax for deriving one list from another is concise. These expressions are known as list comprehensions. Python list comprehensions make it extremely simple to apply a function or filter to a list of items. List comprehensions can be very useful when used correctly, but they can also be very unreadable if used incorrectly.

Let us remove all elements which are divisible by 2.

We can achieve that easily by list comprehension as given below:

# function which remove multiple items from the list
def removeMultiple(givenlist):
    # using list comprehension
    givenlist = [element for element in givenlist if element % 2 != 0]
    # return the given list
    return(givenlist)


# Driver code
# Given list
givenlist = [1, 2, 3, 4, 5, 6, 7, 8]
# passing the list to removeMultiple function
print(removeMultiple(givenlist))

Output:

[1, 3, 5, 7]

Related Programs:

Python : How to Remove Multiple Elements from List ? Read More »