Author name: Vikram Chiluka

Sort a Dictionary by Value

Python: Sort a Dictionary by Value

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.

Examples:

Sorting values in ascending order:

Input:

dictionary = {'this': 70, 'is': 20, 'BTechGeeks': 100, 'Platform': 25}

Output:

is : 20
Platform : 25
this : 70
BTechGeeks : 100

Sorting values in descending order:

Input:

dictionary = {'this': 70, 'is': 20, 'BTechGeeks': 100, 'Platform': 25}

Output:

BTechGeeks : 100
this : 70
Platform : 25
is : 20

Sort a Dictionary by Value in Python

1)Sorted() function

Sorting any sequence in Python is a breeze thanks to the built-in method sorted(), which does all of the heavy lifting for you.
Sorted() sorts any sequence (list, tuple) and always returns a list with the elements sorted in the same order as the original sequence.

Syntax:

sorted(iterable, key, reverse)

Parameters:

sorted accepts three parameters, two of which are optional.

Iterable:  a sequence (list, tuple, or string) or a collection (dictionary, set, or frozenset) or any other iterator that must be sorted.
Key(optional):   A function that can be used as a key or as the basis for sort comparison.
Reverse(optional):   If set to true, the iterable is sorted in reverse (descending) order; otherwise, it is set to false.

2)Using sorted() +items() + Lambda function

We’ll use the sorted() function and transfer a key function that returns the first index element of the tuple, i.e. the value field from the key/value pair, to sort dictionary elements by value.

Below is the implementation:

# Given dictionary
dictionary = {'this': 70, 'is': 20, 'BTechGeeks': 100, 'Platform': 25}
# convert the dictionary to list using items()
dictitems = dictionary.items()
# Using sorted() traverse this list in
# using key to sort by values
for i in sorted(dictitems, key=lambda x: x[1]):
    # print key and value
    print(i[0], ":", i[1])

Output:

is : 20
Platform : 25
this : 70
BTechGeeks : 100

3)Using sorted() +items() + Lambda function to sort in reverse order

This can be accomplished by simply passing an attribute to the sorted() function, such as reverse=True.

Below is the implementation:

# Given dictionary
dictionary = {'this': 70, 'is': 20, 'BTechGeeks': 100, 'Platform': 25}
# convert the dictionary to list using items()
dictitems = dictionary.items()
# Using sorted() traverse this list in
# using key to sort by values
for i in sorted(dictitems, key=lambda x: x[1], reverse=True):
    # print key and value
    print(i[0], ":", i[1])

Output:

BTechGeeks : 100
this : 70
Platform : 25
is : 20

4)Using sorted() +items() + itemgetter in Python

To achieve similar functionality, Itemgetter can be used instead of the lambda function. The same as sorted() and lambda, but with a different internal implementation. It takes dictionary keys and converts them to tuples. It reduces overhead while also being faster and more efficient. To function, the “operator” module must be imported.

The itemgetter object can be passed as a key argument to the sorted() function to retrieve the value field from each key-value item of the dictionary while sorting.

Below is the implementation:

import operator
# Given dictionary
dictionary = {'this': 70, 'is': 20, 'BTechGeeks': 100, 'Platform': 25}
# using itemgetter
dictionary = dict(sorted(dictionary.items(),
                         key=operator.itemgetter(1)))
# print dictionary
print(dictionary)

Output:

{'is': 20, 'Platform': 25, 'this': 70, 'BTechGeeks': 100}

5)Using sorted() +items() + itemgetter  to sort in descending order in Python

This can be accomplished by simply passing an attribute to the sorted() function, such as reverse=True.

Below is the implementation:

import operator
# Given dictionary
dictionary = {'this': 70, 'is': 20, 'BTechGeeks': 100, 'Platform': 25}
# using itemgetter
dictionary = dict(sorted(dictionary.items(),
                         key=operator.itemgetter(1), reverse=True))
# print dictionary
print(dictionary)

Output:

{'BTechGeeks': 100, 'this': 70, 'Platform': 25, 'is': 20}

Related Programs:

Python: Sort a Dictionary by Value Read More »

How to Unpack List, Tuple or Dictionary to Function arguments using args and kwargs

Python : How to Unpack List, Tuple or Dictionary to Function arguments using * and **

Unpack elements in a list or tuple to function arguments

1)Args(*)

In Python function definitions, the special syntax *args is used to pass a variable number of arguments to a function. It is used to pass a variable-length, non-keyworded argument list.

To take in a variable number of arguments, the syntax is to use the symbol *; by convention, it is often used with the word args.
*args enables you to accept more arguments than the number of formal arguments you previously defined. With *args, you can add any number of extra arguments to your existing formal parameters (including zero extra arguments).
For instance, suppose we want to create a multiply function that can take any number of arguments and multiply them all together. It is possible.

Example:

i) Unpacking a list

Below is the implementation:

# givenlist
givenlist = ['hello', 'this', 'is', 'BTechGeeks']
# unpack the list
print(*givenlist)

Output:

hello this is BTechGeeks

ii)Unpacking a tuple

Below is the implementation:

# giventuple
giventuple = ('hello', 'this', 'is', 'BTechGeeks')
# unpack the tuple
print(*giventuple)

Output:

hello this is BTechGeeks

However, we must ensure that the elements of the list or tuple are exactly equal to function parameters. Otherwise, it will result in an error. As a result, it is commonly used with functions that accept variable length arguments.

Below is the implementation:

def calculateSum(*args):
    # Arguments of variable length are accepted by this function.
    num = len(args)
    if num == 0:
        return 0
    sumargs = 0
    for element in args:
        sumargs += element
    return sumargs


list1 = [1, 2, 3]
# passing list to calculateSum function
print(calculateSum(*list1))
list2 = [1, 2, 3, 4, 5, 6, 7]
# passing list to calculateSum function
print(calculateSum(*list2))

Output:

6
28

2)Kwargs(**)

In Python function definitions, the special syntax **kwargs is used to pass a keyworded, variable-length argument list. We call ourselves kwargs with a double star. The reason for this is that the double star allows us to pass keyword arguments through (and any number of them).

** is another symbol provided by Python. When it is prefixed with a dictionary, all of the key value pairs in the dictionary are unpacked to function arguments.

Examples:

1)

Below is the implementation:

def printDict(price, name, Model):
    print("price =", price)
    print("name =", name)
    print("Model =", Model)


# given dictionary
dictionary = {'price': 100, 'name': 'Apple', 'Model': '12pro'}
# printing dictionary arguments using kwargs**
printDict(**dictionary)

Output:

price = 100
name = Apple
Model = 12pro

Related Programs:

Python : How to Unpack List, Tuple or Dictionary to Function arguments using * and ** Read More »

Remove all Numbers from String

Python: Remove all Numbers from String

A Python string is a collection of characters surrounded by single, double, or triple quotes. The computer does not understand the characters; instead, it stores the manipulated character as a combination of 0’s and 1’s internally.

Examples:

Input:

string = "This is 2021 BTech21Geeks"

Output:

This is  BTechGeeks

Delete all Numbers from the string

There are several ways to remove all numbers from the string some of them are:

Method #1:Using string.join() method

The string.join(iterable) method takes an iterable object as input, joins its elements together using the string’s value as a separator, and returns the resulting string as output.

To remove numbers from the string, we will first iterate through it and select non-digit values, which we will then pass to the string.

To join them, use the join() method and output the resulting string with non-digit characters.

Below is the implementation:

# given string
string = "This is 2021 BTech21Geeks"
# using string.join() method by traversing the string and element is not digit
string = ''.join((element for element in string if not element.isdigit()))
# print the string
print(string)

Output:

This is  BTechGeeks

Method #2:Using translate() function

This method makes use of the string Python library. maketrans() uses a string object to separate numbers from the given string. Following that, a translation table is created in which each digit character, i.e. ‘0’ to ‘9,’ is mapped to None, and this translation table is passed to the translate() function.

The example below creates a translation table and replaces characters in a string based on this table, removing all numbers from the string.

Below is the implementation:

import string
# given string
string = "This is 2021 BTech21Geeks"

# the digits in string  are mapped to empty character
table = str.maketrans('', '', string.digits)

# remove all numbers from string
string = string.translate(translation_table)
# print the string
print(string)

Output:

This is  BTechGeeks

Method #3:Using Regex

Python includes a regex module with a built-in function sub() for removing numbers from strings. This method uses a replacement string to replace all occurrences of the given pattern in the string. If the pattern is not found in the string, the same string is returned.

In the following example, we use r'[0-9]’ as a pattern and an empty string as a replacement string. This pattern matches all of the numbers in the given string, and the sub() function replaces all of the digits that match with an empty string. It then deletes all of the numbers that match.

Below is the implementation:

import re
# given string
string = "This is 2021 BTech21Geeks"
# digits pattern
digitspattern = r'[0-9]'

# Replace all of the digits in the string with an empty string.
string = re.sub(digitspattern, '', string)

# print the string
print(string)

Output:

This is  BTechGeeks

Method #4:Using filter() and join()

In the generating expression, this example employs the filter() and lambda functions. It filters or deletes all of the numbers from the given string and then joins the remaining characters to form a new string.

The original string and the lambda expression are passed to the filter() function as arguments. We started by removing all digit characters from a string, then we joined all of the remaining characters.

Below is the implementation:

# given string
string = "This is 2021 BTech21Geeks"
# removing all digits
string = ''.join(filter(lambda x: not x.isdigit(), string))

# print the string
print(string)

Output:

This is  BTechGeeks

Related Programs:

Python: Remove all Numbers from String Read More »

Set add() vs update()

Python Set: add() vs update()

A set in Python is a data structure that is analogous to a set in mathematics. It can have any number of elements; the order of the elements in a set is undefined. You can add and delete elements from a set, iterate through the set’s elements, and perform standard set operations (union, intersection, difference). Aside from that, you can see if an element is a member of a set.

In contrast to arrays, where the elements are stored in an ordered list, the order of elements in a set is undefined (moreover, the set elements are usually not stored in order of appearance in the set; this allows checking if an element belongs to a set faster than just going through all the elements of the set).

Add vs Update in Set

In this article, we will look at the main differences between Python’s add() and update() functions for Set.

1)add() function

If the element is not already present in the set, the set add() method adds it.

Syntax:

set.add(element)

Parameters:

add() accepts a single parameter (element) that must be added to the set.

Return:

The add() method does not return any value.

2)update() function

set’s update() function adds elements from another set (passed as an argument) to the set.

Syntax:

set.update(*args)

Parameters:

The Update() method only accepts one argument. A set, list, tuples, or dictionary can be used as the single argument. It converts and adds to the set automatically.

Return:

This method simply adds args to set and returns null.

3) add() vs update() difference

  • To add a single element, use the add() function. To add multiple elements to a set, use the update() function.
  • add() is quicker than update().
  • Only immutable parameters are accepted by add (). In contrast, accepts iterable sequences.
  • add() only takes one parameter, whereas update() can take multiple sequences.

We will discuss this one by one

4)Difference #1:Number of items to be added to set

i)adding single element using add()

We can only add one element to the set using the add() function.

Below is the implementation:

# given set
givenset = {'hello', 'this', 'is', 'BTeechGeeks'}
# adding element to set using add()
givenset.add('Python')
# print the set
print(givenset)

Output:

{'hello', 'BTeechGeeks', 'this', 'is', 'Python'}

ii)adding multiple elements using update()

In contrast, the update() function can be used to add multiple elements to the set in a single line.

Below is the implementation:

# given set
givenset = {'hello', 'this', 'is', 'BTeechGeeks'}
# adding elements to set using update()
givenset.update(['Python', '2021', 'platform'])
# print the set
print(givenset)

Output:

{'2021', 'platform', 'is', 'BTeechGeeks', 'this', 'Python', 'hello'}

5)Difference #2:Execution time

Add() adds a single element to the set, whereas update() iterates over the given sequences and adds them to the set. As a result, add() outperforms the update() function in terms of performance.

6)Difference #3: Mutable and immutable parameters in add() and update() function

i)add() function

The add() function accepts immutable arguments, which means that we can pass int, strings, bytes, frozen sets, tuples, or any other immutable object to it.

So, if we try to pass a mutable object, such as a list, to the add() function, we will get an error.

Below is the implementation:

# given set
givenset = {'hello', 'this', 'is', 'BTeechGeeks'}
# adding elements to set using add()
givenset.add(['Python', '2021', 'platform'])
# print the set
print(givenset)

Output:

Traceback (most recent call last):
  File "/home/520c50fb7c3daaa8db99bf168af58f53.py", line 4, in <module>
    givenset.add(['Python', '2021', 'platform'])
TypeError: unhashable type: 'list'

ii)update() function

The update() function only accepts iterable sequences. If we pass a list to the update() function, it will add all of the elements in the list to the set.

Below is the implementation:

# given set
givenset = {'hello', 'this', 'is', 'BTeechGeeks'}
# adding elements to set using update()
givenset.update(['Python', '2021', 'platform'])
# print the set
print(givenset)

Output:

{'2021', 'platform', 'is', 'BTeechGeeks', 'this', 'Python', 'hello'}

7)Difference #4:Adding multiple elements using update

We can only pass one argument to the add() function, and it will add that element to the set. In contrast, we can pass multiple arguments, i.e. multiple iterable sequences, when calling the update() function.

Below is the implementation:

# given set
givenset = {'hello', 'this', 'is', 'BTeechGeeks'}
# adding elements to set using update()
givenset.update(['Python', '2021'], ['platform', 'online'], ('India', 122))
# print the set
print(givenset)

Output:

{'hello', 'is', '2021', 'platform', 'online', 122, 'India', 'Python', 'this', 'BTeechGeeks'}

Related Programs:

Python Set: add() vs update() Read More »

Find Duplicates in a list with Frequency Count and index positions

Python: Find Duplicates in a list with Frequency Count and index positions

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 find Duplicate elements in a list with their respective frequencies and index positions.

Example:

I)Without indices

Input:

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

Output:

element = 1 frequency : 3
element = 2 frequency : 2

II)With Indices

Input:

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

Output:

element = 1 frequency : 3 indices : [0, 3, 5]
element = 2 frequency : 2 indices : [1, 4]

Find Duplicates in a list

There are several ways to find duplicates in a list some of them are:

Method #1:Using set method

  • Remove all duplicates from the list by converting it to a set.
  • Now, traverse the set and use the count() function to determine the frequency of each element.
  • If the frequency is greater than 1 then print the element and frequency

Below is the implementation:

# givenlist
givenlist = [1, 2, 3, 1, 2, 1, 5, 6, 7, 8, 9]
# converting givenlist to set
setlist = set(givenlist)
# Traverse the set
for element in setlist:
    # counting the frequency of element if it is greater than 1 then print it
    frequency = givenlist.count(element)
    if(frequency > 1):
        # print the element and frequency
        print('element =', element, 'frequency :', frequency)

Output:

element = 1 frequency : 3
element = 2 frequency : 2

Time Complexity: O(n^2)

Method #2:Using dictionary

We’ll write a function that takes a list and prints the duplicate elements in that list, as well as their frequency counts.

Approach:

  • This function produces a new dictionary when it is called. The program then goes through each element in the provided list one by one. It examines each variable to see if it is present in the dictionary keys.
  • If the element does not appear in the dictionary keys, it is added to the dictionary as a key with the value of 1.
    If the element is present in dictionary keys, the value of that key is increased by one.
  • Traverse the dictionary
  • If the frequency is greater than 1 then print the element and frequency

Below is the implementation:

# function which print the duplicates
def printDuplicates(givenlist):
    # taking a empty dictionary
    freq = {}
    # Traverse the list
    for element in givenlist:
        # if the element is in freq dictionary then add its count
        if element in freq.keys():
            freq[element] += 1
        else:
            freq[element] = 1

    # Traverse the freq dictionary and print the duplicate elements and frequency
    for key in freq:
        # if value/count is greater than 1 the print it
        if(freq[key] > 1):
            print('element =', key, 'frequency :', freq[key])


# givenlist
givenlist = [1, 2, 3, 1, 2, 1, 5, 6, 7, 8, 9]
# passing list to printDuplicates function
printDuplicates(givenlist)

Output:

element = 1 frequency : 3
element = 2 frequency : 2

Time Complexity: O(n)

Method #3:Using Counter() function

We can use an iterable or any dict like mapping to construct a Counter class object. This Counter object keeps track of how many times each variable in the iterable has been counted. Let’s use the Counter object to locate and count duplicates in a list.

This function is similar to first two points in method 2

Below is the implementation:

from collections import Counter
# function which print the duplicates


def printDuplicates(givenlist):
    # using Counter function to calculate frequencies
    freq = Counter(givenlist)

    # Traverse the freq dictionary and print the duplicate elements and frequency
    for key in freq:
        # if value/count is greater than 1 the print it
        if(freq[key] > 1):
            print('element =', key, 'frequency :', freq[key])


# givenlist
givenlist = [1, 2, 3, 1, 2, 1, 5, 6, 7, 8, 9]
# passing list to printDuplicates function
printDuplicates(givenlist)

Output:

element = 1 frequency : 3
element = 2 frequency : 2

Time Complexity: O(n)

Method #4:Finding indices and frequency of duplicate elements

Approach:

  • let us take starting index as 0
  • This function produces a new dictionary when it is called. The program then goes through each element in the provided list one by one. It examines each variable to see if it is present in the dictionary keys.
  • Then iterates through each element in the list one by one, keeping track of the index positions.
  • Then, for each element, it checks to see if it already exists in the dictionary keys.
  • If it doesn’t, it creates a new key-value pair in the dictionary, with the element as the key and a list object of two items as the value. 1)count as 1 2) index list with current index position
  • If the element is found in the dictionary keys, the frequency count in the value field is increased, and the index location in the index list is added.
  • Increment the index by 1 for every iteration
  • Traverse the dictionary
  • If the frequency is greater than 1 then print the element and frequency and indices

Below is the implementation:

def printDuplicates(givenlist):
    # taking a empty dictionary
    freq = {}
    # taking index =0
    index = 0
    # Traverse the list
    for element in givenlist:
        # if the element is in freq dictionary then add its count and index
        if element in freq.keys():
            freq[element][0] += 1
            freq[element][1].append(index)
        else:
            freq[element] = [1, [index]]
        # increment the index
        index += 1

    # Traverse the freq dictionary and print the duplicate elements and frequency
    for key in freq:
        # if value/count is greater than 1 the print it
        if(freq[key][0] > 1):
            print('element =', key, 'frequency :',
                  freq[key][0], 'indices :', freq[key][1])


# givenlist
givenlist = [1, 2, 3, 1, 2, 1, 5, 6, 7, 8, 9]
# passing list to printDuplicates function
printDuplicates(givenlist)

Output:

element = 1 frequency : 3 indices : [0, 3, 5]
element = 2 frequency : 2 indices : [1, 4]

Time Complexity: O(n)

 
Related Programs:

Python: Find Duplicates in a list with Frequency Count and index positions Read More »

String – Replace() Method

Python String – Replace() Method

A string is a character sequence.
A character is nothing more than a symbol. The English language, for example, has 26 characters.
Computers do not work with characters, but rather with numbers (binary). Despite the very fact that you simply see characters on your screen, they’re internally stored and manipulated as a series of 0s and 1s.
Encoding is the process of converting a character to a number, and decoding is the reverse process. ASCII and Unicode are two of the most common encodings.
A string in Python may be a sequence of Unicode characters. Unicode was created to include every character in all languages and to bring encoding uniformity. Python Unicode can teach you everything you need to know about Unicode.

String Replace() Function

1)replace() function

replace() is a built-in Python function that returns a copy of the string in which all occurrences of a substring are replaced with another substring.

Syntax:

given_string.replace(old, new, count)

Parameters:

  • old−This is an old substring that must get replaced .
  • new − this is often a replacement substring which will replace the old one.
  • max − Only the primary count occurrences are replaced if the optional argument max is provided.

Return:
This method returns a string copy during which all occurrences of substring old are replaced with new. Only the primary count occurrences are replaced if the optional argument max is provided.

2)Replace all instances of a character or string in a string:

Assume we have a string, and now replace all occurrences of ‘e’ with ‘q’.

Below is the implementation:

# Function which replaces the string
def replaceString(string, oldstring, replacestring):
    # using replace
    resultstring = string.replace(oldstring, replacestring)

    # return the final string
    return resultstring


# Driver code
# given string
string = "This is BTechGeeks new online learning platform"
# string which needs to be replaced
oldstring = 'e'
# replacing string/new string
replacestring = 't'
# passing these strings to replaceString function
print(replaceString(string, oldstring, replacestring))

Output:

This is BTtchGttks ntw onlint ltarning platform

3)Replace only first two occurences of string:

Instead of replacing all occurrences of a character in a string, we can use the replace() function’s count argument to replace only the first few occurrences of a character.

Below is the implementation:

# Function which replaces the string
def replaceMultipleString(string, oldstring, replacestring):
    # using replace
    # providing count =2
    resultstring = string.replace(oldstring, replacestring, 2)

    # return the final string
    return resultstring


# Driver code
# given string
string = "Hello this is BTechGeeks"
# string which needs to be replaced
oldstring = 'e'
# replacing string/new string
replacestring = '$$$'
# passing these strings to replaceMultipleString function
print(replaceMultipleString(string, oldstring, replacestring))

Output:

H$$$llo this is BT$$$chGeeks

4)Replace the first occurrence of a given substring in a string with another character

If we only want to replace the first occurrences of a substring in a string with another character or substring, we must use the replace() function with the count argument set to 1.

Below is the implementation:

# Function which replaces the string
def replaceMultipleString(string, oldstring, replacestring):
    # using replace
    # providing count =2
    resultstring = string.replace(oldstring, replacestring, 1)

    # return the final string
    return resultstring


# Driver code
# given string
string = "Hello this is BTechGeeks"
# string which needs to be replaced
oldstring = 'is'
# replacing string/new string
replacestring = 't'
# passing these strings to replaceMultipleString function
print(replaceMultipleString(string, oldstring, replacestring))

Output:

Hello tht is BTechGeeks

Related Programs:

Python String – Replace() Method Read More »

Remove First N Characters from String in Python

Strings are one of the most commonly used types in Python. We can easily make them by enclosing characters in quotes. Python considers single quotes to be the same as double quotes. String creation is as easy as assigning a value to a variable.

Given a string, the task is to remove first n characters from string.

Examples:

Input:

string="BTechGeeks" n=3

Output:

chGeeks

Remove First N Characters from String

There are several ways to remove first n characters from string some of them are:

Method #1:Using slicing

It returns the characters of the string as a new string from index position start to end -1. The default values for start and end are 0 and Z, where Z is the length of the string. If neither start nor end are specified, it selects all characters in the string, from 0 to size-1, and creates a new string from those characters.

This slicing technique can be used to cut out a piece of string that includes all characters except the first N characters.

Below is the implementation:

# function which removes first n characters of string
def removeFirstN(string, n):
    # removing first n characters of string
    string = string[n:]
    # return the string
    return string


# given string
string = "BTechGeeks"
# given n
n = 3
# passing string and n to removeFirstN function
print(removeFirstN(string, n))

Output:

chGeeks

Method #2 : Using for loop

To delete the first N characters from a string, we can iterate through the string’s characters one by one, selecting all characters from index position N until the end of the string.

Below is the implementation:

# function which removes first n characters of string
def removeFirstN(string, n):
    # taking a empty string
    newstr = ""
    # removing first n characters of string using for loop
    # Traverse the string from n to end
    for i in range(n, len(string)):
        newstr = newstr+string[i]

    # return the string
    return newstr


# given string
string = "BTechGeeks"
# given n
n = 3
# passing string and n to removeFirstN function
print(removeFirstN(string, n))

Output:

chGeeks

Method #3 :Using regex to remove first two characters

In Python, we can use regex to match two groups in a string, i.e.

Group 1: The first N characters in a string
Group 2 consists of every character in the string except the first N characters.
The string is then modified by replacing both groups with a single group, group 2.

Below is the implementation:

import re
def removeGroup(k):
    # Only group 1 should be returned from the match object.
        # Other groups should be deleted.
    return k.group(2)
# given string
string = "BTechGeeks"
result = re.sub("(^.{2})(.*)", removeGroup, string)
print(result)

Output:

echGeeks

Related Programs:

Remove First N Characters from String in Python Read More »

Remove Last N Characters from String in Python

Strings are one of the most commonly used types in Python. We can easily make them by enclosing characters in quotes. Python considers single quotes to be the same as double quotes. String creation is as easy as assigning a value to a variable.

Given a string, the task is to remove last n characters from string.

Examples:

Input:

string="BTechGeeks" n=3

Output:

BTechGe

Remove Last N Characters from String

There are several ways to remove last n characters from string some of them are:

Method #1:Using slicing

It returns the characters of the string as a new string from index position start to end -1. The default values for start and end are 0 and Z, where Z is the length of the string. If neither start nor end are specified, it selects all characters in the string, from 0 to size-1, and creates a new string from those characters.

This slicing technique can be used to cut out a piece of string that includes all characters except the last N characters.

Below is the implementation:

# function which removes last n characters of string
def removeLastN(string, n):
    # calculate the size of string
    size = len(string)
    # removing last n characters of string
    string = string[:size-n]
    # return the string
    return string


# given string
string = "BTechGeeks"
# given n
n = 3
# passing string and n to removeLastN function
print(removeLastN(string, n))

Output:

BTechGe

Method #2 : Using for loop

To delete the last N characters from a string, we can iterate through the string’s characters one by one, selecting all characters from index position 0 until the size – n of the string.

Below is the implementation:

# function which removes last n characters of string
def removeLastN(string, n):
    # taking a empty string
    newstr = ""
    # removing last n characters of string using for loop
    # Traverse the string from 0 to sizr-n
    for i in range(0, len(string)-n):
        newstr = newstr+string[i]

    # return the string
    return newstr


# given string
string = "BTechGeeks"
# given n
n = 3
# passing string and n to removelastN function
print(removeLastN(string, n))

Output:

BTechGe

Method #3 :Using regex to remove last two characters

In Python, we can use regex to match two groups in a string, i.e.

Group 1: The first N characters in a string
Group 2 consists of every character in the string except the first N characters.
The string is then modified by replacing both groups with a single group, group 1.

Below is the implementation:

import re

def removeGroup(k):
    # Only group 1 should be returned from the match object.
        # Other groups should be deleted.
    return k.group(1)

# given string
string = "BTechGeeks"
result = re.sub("(.*)(.{2}$)", removeGroup, string)
print(result)

Output:

BTechGee

 
Related Programs:

Remove Last N Characters from String in Python Read More »

Python: Remove All Elements from Set using Clear()/Difference_Update()/Discard()

Python set is a list of items that are not ordered. – Each element in the set must be unique and immutable, and duplicate elements are removed from the sets. Sets are mutable, which means they can be changed after they have been created.

The elements of the set, unlike other Python sets, do not have an index, which means we cannot access any element of the set directly using the index. To get the list of elements, we can either print them all at once or loop through the collection.

Examples:

Input:

givenset= {'this', 'is', 'BTechGeeks'}

Output:

set()

Delete all the elements from the set

There are several ways to remove all the elements from the set some of them are:

Method #1:Using discard() function

In Python, the built-in method discard() removes an element from a collection only if it is already present. If the element is missing from the list, no error or exception is thrown, and the original set is printed.

Approach:

  • While iterating over a set, we cannot modify it.
  • So We will make a list of the set’s elements, then iterate through that list, removing each element from the set.

Below is the implementation:

# given set
givenset = {'this', 'is', 'BTechGeeks'}

# using for loop to traverse the set
for element in list(givenset):
    # remove that element from set
    givenset.discard(element)
# print the set
print(givenset)

Output:

set()

Method #2:Using clear() function

The clear() method clears the set of all elements.

syntax:

given_set.clear()

parameters:

The clear() method accepts no parameters.

Return :

The clear() method does not return a value.

Below is the implementation:

# given set
givenset = {'this', 'is', 'BTechGeeks'}

# using clear()
givenset.clear()
# print the set
print(givenset)

Output:

set()

Method #3:Using difference_update() method

The Set class in Python has a function called difference update() that takes a sequence as an argument and removes all of the elements from the set. let us use this method to remove all the elements from the set

We can pass given set as parameter for the difference_update() function

Below is the implementation:

# given set
givenset = {'this', 'is', 'BTechGeeks'}
# using difference_update()
givenset.difference_update(givenset)
# print the set
print(givenset)

Output:

set()

Related Programs:

Python: Remove All Elements from Set using Clear()/Difference_Update()/Discard() Read More »

Python : How to Insert an element at specific index in List ?

Lists are similar to dynamically sized arrays, which are declared in other languages(e.g., vector in C++ and ArrayList in Java). Lists do not have to be homogeneous all of the time, which makes it a very useful tool in Python. DataTypes such as Integers, Strings, and Objects can all be included in a single list. Lists are mutable, which means they can be changed after they’ve been created.

An index refers to a position within an list.

Given, a list the task is to insert an element at specific index in given list.

Insert an element at Specific Index in List

1)Insert() function

Syntax:

givenlist.insert(index, element)

Parameters:

index - the position in the array at which the element must be inserted.
element - the element that will be added to the list.

Return:

This method does not return a value, but instead inserts the specified element at the specified index.

2)Inserting an element at a specific position

Suppose we want to insert ‘python’ in a givenlist at index 3 we can pass arguments like

insert(3,value) where value=‘python’

Below is the implementation:

# given list
givenlist = ['hello', 'this', 'is', 'BTechGeeks']
# given value
value = 'python'
# given index
index = 3
# inserting the given value at given index
givenlist.insert(index, value)
# print the list
print(givenlist)

Output:

['hello', 'this', 'is', 'python', 'BTechGeeks']

3)Inserting element at the first position of the list

We know that the starting index of list is 0 so we give 0 as index while inserting the given value.

Below is the implementation:

# given list
givenlist = ['hello', 'this', 'is', 'BTechGeeks']
# given value
value = 'python'
# inserting the given value at starting position
givenlist.insert(0, value)
# print the list
print(givenlist)

Output:

['python', 'hello', 'this', 'is', 'BTechGeeks']

4)Inserting element at the end position of the list

We know that the last index of the list is len(list)-1 to insert element at end we use len(list) as parameter.

Passing this index to insert function inserts the element at the end of the list.

Below is the implementation:

# given list
givenlist = ['hello', 'this', 'is', 'BTechGeeks']
# given value
value = 'python'
# inserting the given value at end position
givenlist.insert(len(givenlist), value)
# print the list
print(givenlist)

Output:

['hello', 'this', 'is', 'BTechGeeks', 'python']

5)Insert all elements of second list at specific index in given list

By slicing we can insert it easily .

Splice given list from 0 to index-1 and merge all of list2’s elements into it. Then, from index to the end of the list, merge all of the remaining elements.

Below is the implementation:

# given list
givenlist = ['hello', 'this', 'is', 'BTechGeeks']
# given value
givenlist2 = ['welcome', 'to', 'python']
# given index
index = 2
# inserting the given value using slicing
givenlist = givenlist[:index]+givenlist2+givenlist[index:]
# print the list
print(givenlist)

Output:

['hello', 'this', 'welcome', 'to', 'python', 'is', 'BTechGeeks']

Related Programs:

Python : How to Insert an element at specific index in List ? Read More »