Author name: Vikram Chiluka

Python: How to Convert Integer to String

Integer:

An integer, on the other hand, is a whole number, the kind you started counting out in school when you first heard about numbers. In Python 3, an integer can be any length up to the computer’s memory limit, so you’ll probably never run out of integers to use.

String:

In computer programming, a string is a sequence of characters that can be used as a literal constant or as a variable. A string is a finite sequence of symbols chosen from an alphabet in formal languages, which are used in mathematical logic and theoretical computer science.

Example:

Input:

IntegerValue=23

Output:

StringValue: 23
Type : <class 'str'>

Integer to String conversion

The following is a list of possible python methods for converting an integer to a string:

Method #1: Using str() function

The str() function in Python can be used to convert an integer to a string. Any python data type can be passed to the str() function, which converts it to a string.

The str() function converts an object to a string. An int, char, or string may be used as the object. It returns an empty string if the object is not passed as an argument.

Below is the implementation:

# given integer
intvalue = 23
# converting to string using str() function
strvalue = str(intvalue)
# printing the value and type
print("String value :", strvalue)
print("type :", type(strvalue))

Output:

String value : 23
type : <class 'str'>

Method #2: Using “%s” keyword

This is the most traditional method. We may insert objects within a string using positional formatting.

Below is the implementation:

# given integer
intvalue = 23
# converting to string using str() function
strvalue = "%s" % intvalue
# printing the value and type
print("String value :", strvalue)
print("type :", type(strvalue))

Output:

String value : 23
type : <class 'str'>

Method #3:Using format() function

Python’s string class has a format() feature. It converts the string by substituting the values of the variables for the placeholders specified within.

Below is the implementation:

# given integer
intvalue = 23
# converting to string using format() function
strvalue = "{}".format(intvalue)
# printing the value and type
print("String value :", strvalue)
print("type :", type(strvalue))

Output:

String value : 23
type : <class 'str'>

Method #4: Using f-strings

F-strings allow you to use a simple syntax to insert expressions within string literals. It’s worth noting that an f-string is actually an expression that is evaluated at runtime rather than a fixed value. An f-string is a literal string in Python source code that includes expressions within braces and is prefixed with ‘f’. The values are substituted for the expressions.

Below is the implementation:

# given integer
intvalue = 23
# converting to string using f-strings
strvalue = f'{intvalue}'
# printing the value and type
print("String value :", strvalue)
print("type :", type(strvalue))

Output:

String value : 23
type : <class 'str'>

Method #5: Using __str__()

Internally, the str(object) function calls __str__() on the passed argument object. As a result, we may use the object’s __str__() method directly. In the previous example, we passed an integer to the str() function. Instead, we can use the int object’s __str__() function to get a string representation of the integer.

# given integer
intvalue = 23
# converting to string using __str__
strvalue = intvalue.__str__()
# printing the value and type
print("String value :", strvalue)
print("type :", type(strvalue))

Output:

String value : 23
type : <class 'str'>

Related Programs:

Python: How to Convert Integer to String Read More »

Python: Remove First Element from a List

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

Examples:

Input:

givenlist = ["Hello", "Btech" , "Geeks" ,"is" ,"new" ,"online" ]

Output:

['Btech', 'Geeks', 'is', 'new', 'online']

Explanation:

Hello is the first element in givenlist hence it is deleted.

Remove the First Element of a List

There are several ways to remove the first item from the list some of them are:

>Method #1:Using slicing

Lists can be cut in Python, as we all know. Slicing is a method of removing the first item from a list. The goal is to make a sublist that contains all of the elements of the list except the first one. Because the slice operation returns a new list, we must assign the new list to the original list. To accomplish this, use the expression l = l[1:], where l is your list. l[1:] is an abbreviation for l[0:len(l)-1].

Below is the implementation:

# Function which removes first element
def removeFirstElement(givenlist):
    # using slicing
    givenlist = givenlist[1:]
    # return the result list
    return givenlist


# Driver code
# given list
givenlist = ["Hello", "Btech", "Geeks", "is", "new", "online"]
# passing list to remove first element
print(removeFirstElement(givenlist))

Output:

['Btech', 'Geeks', 'is', 'new', 'online']

>Method #2:Using del keyword

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.

The index of first item in list is 0.

Below is the implementation:

# Function which removes first element
def removeFirstElement(givenlist):
    # using del keyword
    del givenlist[0]
    # return the result list
    return givenlist


# Driver code
# given list
givenlist = ["Hello", "Btech", "Geeks", "is", "new", "online"]
# passing list to remove first element
print(removeFirstElement(givenlist))

Output:

['Btech', 'Geeks', 'is', 'new', 'online']

>Method #3:Using pop() function

The list class in Python has a function called pop(index), which takes an optional argument index and deletes the element at that index. If no justification is given, it deletes the last element of the list by default.

The index of first element in list is 0.

Below is the implementation:

# Function which removes first element
def removeFirstElement(givenlist):
    # using pop function
    givenlist.pop(0)
    # return the result list
    return givenlist


# Driver code
# given list
givenlist = ["Hello", "Btech", "Geeks", "is", "new", "online"]
# passing list to remove first element
print(removeFirstElement(givenlist))

Output:

['Btech', 'Geeks', 'is', 'new', 'online']

>Method #4:Using remove() function

The list class in Python has a function remove(value) that deletes the first occurrence of a given value from the list. This can be used to remove the first item from the list. Select the first element from the list and pass it to the remove() function to accomplish this.

Below is the implementation:

# Function which removes first element
def removeFirstElement(givenlist):
    # getting first element of the given list
    firstelement = givenlist[0]
    # using remove function
    givenlist.remove(firstelement)
    # return the result list
    return givenlist


# Driver code
# given list
givenlist = ["Hello", "Btech", "Geeks", "is", "new", "online"]
# passing list to remove first element
print(removeFirstElement(givenlist))

Output:

['Btech', 'Geeks', 'is', 'new', 'online']

>Method #5:Using deque() function

A double-ended queue, or deque, allows you to add and remove elements from either end. The Deque module is a collection library module. It has methods for adding and removing elements that can be directly invoked with arguments.

Convert the given list to a deque and then pop an element from the left. Then add the remaining deque elements to the list.

Below is the implementation:

from collections import deque
# Function which removes first element


def removeFirstElement(givenlist):
    # converting given list to deque
    dequelist = deque(givenlist)
    # using popleft function to remove first element
    dequelist.popleft()
    # Converting deque to list
    givenlist = list(dequelist)
    # return the result list
    return givenlist


# Driver code
# given list
givenlist = ["Hello", "Btech", "Geeks", "is", "new", "online"]
# passing list to remove first element
print(removeFirstElement(givenlist))

Output:

['Btech', 'Geeks', 'is', 'new', 'online']

Related Programs:

Python: Remove First Element from a List Read More »

Python : Convert List of Lists or Nested List to Flat List

Lists are similar to dynamically sized arrays declared in other languages (for example, vector in C++ and ArrayList in Java). Lists do not always have to be homogeneous, which makes it a very useful tool in Python. A single list can contain DataTypes such as Integers, Strings, and Objects. Lists are mutable, which means they can be modified after they are created.

A list of lists is a list object in Python, with each list element being a separate list.

Example:

Input:

listoflists = [ [3 ,6 ,7 ] , [1 , 2, 3 ] , [8 , 7, 6 ] ]

Output:

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

Nested Lists to Flat list Conversion

There are several ways to convert nested list to flat list some of them are:

Method#1:Using extend() function

Extend in Python:

The extend() method appends to the end of a list all the elements of an iterable (list, tuple, string, etc.). All iterable elements are added to the end of list1 in this case.

It adds all the contents of the given iterable to the existing list object. Let’s put this to use and convert a list of lists to a flat list.

Approach:

  • Take a empty list say flatlist
  • Traverse the given list of lists, and for each list within it, extend that list to flatlist.
  • print flatlist

Below is the implementation:

# Function to convert list of lists to flat list
def convertToFlatList(listoflists):
    # Taking empty flat list
    FlatList = []
    # Traverse the given listoflists
    for element in listoflists:
        # Adding this list to flatlist using extend
        FlatList.extend(element)

        # returning the flatlist
    return FlatList


# Driver code
# given listoflists
listoflists = [[3, 6, 7], [1, 2, 3], [8, 7, 6]]
# passing listoflists to convertToFlatList function
print(convertToFlatList(listoflists))

Output:

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

Method #2:Using append() function

Append():

Python’s append() method adds a single item to an existing list. It does not return a new list of items, but rather modifies the original list by appending the item to the end. The size of the list increases by one after executing the method append on it.

Approach:

  • Take a empty list say flatlist
  • Traverse the given list of lists, and then traverse it again using a loop for each list within it, appending all the elements to flatlist.
  • print flatlist.

Below is the implementation:

# Function to convert list of lists to flat list
def convertToFlatList(listoflists):
    # Taking empty flat list
    FlatList = []
    # Traverse the given listoflists
    for element in listoflists:
        # Traverse the inner list
        for loopelement in element:
          # appeend this loopelement
            FlatList.append(loopelement)

        # returning the flatlist
    return FlatList


# Driver code
# given listoflists
listoflists = [[3, 6, 7], [1, 2, 3], [8, 7, 6]]
# passing listoflists to convertToFlatList function
print(convertToFlatList(listoflists))

Output:

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

Method #3:Using List Comprehension

We’ll use list comprehension to iterate over a list of lists, then iterate over the individual elements in each internal list. Then, in a new list, add those elements.

Below is the implementation:

# Function to convert list of lists to flat list
def convertToFlatList(listoflists):
    # Using list Comprehension
    FlatList = [item for element in listoflists for item in element]

    # returning the flatlist
    return FlatList


# Driver code
# given listoflists
listoflists = [[3, 6, 7], [1, 2, 3], [8, 7, 6]]
# passing listoflists to convertToFlatList function
print(convertToFlatList(listoflists))

Output:

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

Related Programs:

Python : Convert List of Lists or Nested List to Flat List Read More »

How to Replace Single or Multiple Characters in a String

Python : How to Replace Single or Multiple Characters in a String ?

A string is a series of characters.

A character is nothing more than a representation of something. For example, the English language has 26 characters.
Computers do not work with characters, but rather with numbers (binary). Despite the fact that you see characters on your screen, they are 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.
In Python, a string is 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.

Examples:

Input:

string="Hello this is BTechGeeks" oldstring='e' replacestring='q'

Output:

Hqllo this is BTqchGqqks

Replace Single or Multiple Characters in a String

There are several ways to replace single or multiple characters in a String of them are:

Python has a string.replace() function

Syntax:

string.replace(old, new , count)

It returns a new string object that is a copy of the existing string with the content replaced. In addition, if count is not provided, it will return a string with all occurrences of ‘old’ replaced with ‘new’ string.
If the count parameter is supplied, it will return a string with the first ‘count’ occurrences of the ‘old’ string replaced with the ‘new’ string.

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 replaceMultipleString(string, oldstring, replacestring):
    # using replace
    resultstring = string.replace(oldstring, replacestring)

    # 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 = 'q'
# passing these strings to replaceMultipleString function
print(replaceMultipleString(string, oldstring, replacestring))

Output:

Hqllo this is BTqchGqqks

Because strings are immutable in Python, we can’t change their contents. As a result, member functions such as replace() produce a new string.

Replace the first n occurrences of a given character / substring in a string with another character / substring.

Suppose we want to replace character ‘e’ with ‘q000’ for first 2 i.e n occurrences then,

# 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 = 'q000'
# passing these strings to replaceMultipleString function
print(replaceMultipleString(string, oldstring, replacestring))

Output:

Hq000llo this is BTq000chGeeks

Replace multiple strings/characters in a string

The string.replace() function can only replace occurrences of a single substring.

But what if we need to replace multiple substrings within the same string?

To replace all occurrences of these three characters ‘e’, ‘h’, and ‘i’ with the string ‘##’ let us write a new function that extends replace().

Below is the implementation:

# Function which replaces the string
def replaceMultipleString(string, oldstring, replacestring):
  # Traverse the old string which needs to be replaced
    for element in oldstring:
        # Check if string is in the original string
        if element in string:
            # Replace the string eith replacestring
            string = string.replace(element, replacestring)

    # return the final string
    return string


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

Output:

H##llo t####s ##s BT##c##G####ks

 
Related Programs:

Python : How to Replace Single or Multiple Characters in a String ? Read More »

How to access characters in string by index

Python : How to access characters in string by index ?

A string is a collection of characters.

A character is simply a representation of something. The English language, for example, has 26 characters.
Computers work with numbers rather than characters (binary). Despite the fact that you see characters on your screen, they are stored and manipulated internally as a series of 0s and 1s.
The process of converting a character to a number is known as encoding, and the process of converting a number to a character is known as decoding. Two of the most common encodings are ASCII and Unicode.
A string in Python is a sequence of Unicode characters. Unicode was created in order to include every character in every language and to bring encoding uniformity. Python Unicode is capable of teaching you everything you need to know about Unicode.

Examples:

Input:

string="Hello this is BTechGeeks" index=3

Output:

l

Retrieve characters in string by index

In this article, we will look at how to access characters in a string using an index.

>1)Accessing characters in a string by index | indexof

Python uses a zero-based indexing system for strings: the first character has index 0, the next has index 1, and so on.

The length of the string – 1 will be the index of the last character.

Suppose we want to access 3rd index in input string

We can implement it as:

# Given string
string = "Hello this is BtechGeeks"
# Given index
index = 3
character = string[index]
# printing the character at given index
print(character)

Output:

l

>2)Using a negative index to access string elements

Negative numbers may be used to specify string indices, in which case indexing is performed from the beginning of the string backward:

The last character is represented by string[-1]

The second-to-last character by string[-2], and so on.

If the length of the string is n, string[-n] returns the first character of the string.

Below is the implementation:

# Given string
string = "Hello this is BtechGeeks"
# given index from end
index = 3
# printing last two characters of string
print("Last character in the given string : ", string[-1])
print("Second Last character in given string : ", string[-2])
# printing n th character from end
print(str(index)+" character from end in given string :", string[-index])

Output:

Last character in the given string :  s
Second Last character in given string :  k
3 character from end in given string : e

>3)Using String Slicing :

# Given string
string = "Hello this is BtechGeeks"
# given start index and end index
startindex = 14
endindex = 19
# using slicing
print(string[startindex:endindex])

Output:

Btech

>4)Accessing Out Of range character in given string using Exceptional Handling:

IndexError will be thrown if an element in a string is accessed that is outside of its range, i.e. greater than its length. As a result, we should always check the size of an element before accessing it by index, i.e.

To handle the error we use exceptional handling in python

Below is the implementation:

# Given string
string = "Hello this is BtechGeeks"
# given index
index = 50
# using try and except
try:
    # if the given index is less than string length then it will print
    print(string[index])
# if index is out of range then it will print out of range
except:
    print("Index out of range")

Output:

Index out of range

 

 
Related Programs:

Python : How to access characters in string by index ? Read More »

Remove Last Element from a List

Python: Remove Last Element from a List

Lists are ordered sequences of objects that may contain a variety of different object types. Members of lists can also be duplicated. Lists in Python are similar to arrays in other programming languages.. However, there is one important distinction. Python lists can contain objects of different data types, while arrays can only contain elements of the same data type.

An index is a position in a list.

Given a list, the task is to remove last element from the given list.

Examples:

Input:

givenlist = ["Btech" , "Geeks" ,"is" ,"new" ,"online" ,"platform" ]

Output:

Btech Geeks is new online

Explanation:

platform is the last element in givenlist hence it is deleted.

Remove the final item from a list

There are several ways to remove the final item from the list some of them are:

Method #1:Using pop() function

The list class in Python has a function called pop(index), which takes an optional argument index and deletes the element at that index. If no justification is given, it deletes the last element of the list by default.

Below is the implementation:

# Function which removes last element
def removeLastElement(givenlist):
    # using pop() function
    givenlist.pop()
    # return the result list
    return givenlist


# Driver code
# given list
givenlist = ["Btech", "Geeks", "is", "new", "online", "platform"]


# passing list to remove last element
print(removeLastElement(givenlist))

Output:

['Btech', 'Geeks', 'is', 'new', 'online']

If the list is empty, the pop([i]) function throws an IndexError since it attempts to pop from an empty list.

Method #2:Using del keyword

The del statement is another way to delete an element from a list by using its index. It differs from the pop() function in that it does not return the element that has been removed. This does not generate a new list, unlike the slicing feature.

Below is the implementation:

# Function which removes last element
def removeLastElement(givenlist):
    # using del keyword
    del givenlist[-1]
    # return the result list
    return givenlist


# Driver code
# given list
givenlist = ["Btech", "Geeks", "is", "new", "online", "platform"]


# passing list to remove last element
print(removeLastElement(givenlist))

Output:

['Btech', 'Geeks', 'is', 'new', 'online']

If the list is empty, the above code raises an IndexError because it tries to reach an index of the list that is out of control.

Method #3: Using slicing

In Python, we know that lists can be cut. Slicing is a technique for removing the last element from a list. The aim is to create a sublist that contains all of the list’s elements except the last one. We must assign the new list to the original list since the slice operation returns a new list. The expression l = l[:-1], where l is your list, can be used to accomplish this. The abbreviation l[:-1] stands for l[0:len(l)-1].

Below is the implementation:

# Function which removes last element
def removeLastElement(givenlist):
    # using slicing
    givenlist = givenlist[:-1]
    # return the result list
    return givenlist


# Driver code
# given list
givenlist = ["Btech", "Geeks", "is", "new", "online", "platform"]


# passing list to remove last element
print(removeLastElement(givenlist))

Output:

['Btech', 'Geeks', 'is', 'new', 'online']

It should be noted that this function does not throw an error if the list is empty, but instead creates a copy of the list, which is not recommended.

Related Programs:

Python: Remove Last Element from a List Read More »

Replace a Character in a String

Python: Replace a Character in a String

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 ,instead, they work with numbers (binary). Even though you see characters on your screen, they are stored and manipulated internally as a series of 0s and 1s.

The process of converting a character to a number is known as encoding, and the reverse process is known as decoding. Some of the most common encodings are ASCII and Unicode.

In Python, a string is a sequence of Unicode characters.. Unicode was created in order to include every character in all languages and bring encoding uniformity. Python Unicode can teach you about Unicode.

This article will go over various methods to replace a character in a string

Examples:

Input:

string="BTechGeeks" oldstring='e' replacestring='p'

Output:

BTpchGppks

Modifying a Character in a String

There are several ways to replace a character in a string some of them are:

Method #1: Using replace() to replace all occurences

The Python string method replace() returns a copy of the string with old occurrences replaced with new, with the number of replacements optionally limited to max.

Syntax :

string .replace(old, new, count)

Parameters:

  • old−This is an old substring that needs to be replaced.
  • new − This is a new substring that will replace the old one.
  • max − Only the first count occurrences are replaced if the optional argument max is provided.

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

Below is the implementation:

# Function which replaces the string
def replaceString(string, oldstring, replacestring):
    # Replace all occurrences of a character in string in python
    resultstring = string.replace(oldstring, replacestring)

    # return the final string
    return resultstring

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

Output:

BTpchGppks

In this case, we passed the character to be replaced ‘e’ as the first argument and the character ‘p’ as the second. The replace() method then returned a copy of the original string by replacing all occurrences of the character’s’ with the character ‘X’.

Because strings are immutable in Python, we cannot change their contents. As a result, the replace() function returns a copy of the string containing the replaced content.

Replace only first two occurences of string:

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

Below is the implementation:

# Function which replaces the string
def replaceString(string, oldstring, replacestring):
    # Replace first 2 occurrences of a character in string in python
    resultstring = string.replace(oldstring, replacestring, 2)

    # return the final string
    return resultstring


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

Output:

BTpchGpeks

In this case, we passed the character to be replaced ‘e’ as the first argument and the character ‘p’ as the second. The third argument was then passed as 2. The third argument is optional and tells the replace() function how many occurrences of the given sub-string should be replaced.

The replace() method then returned a copy of the original string by replacing only the first two occurrences of ‘e’ with the symbol ‘p.’
Because strings are immutable in Python, we cannot change their contents. As a result, the replace() function returns a duplicate of the string with the replaced content.

Method #2:Using for loop

Create an empty string and then iterate through all of the characters in the original string. Add each character to the new string during iteration. However, if a character needs to be replaced, use the replacement character instead.

Below is the implementation:

# Function which replaces the string
def replaceString(string, oldstring, replacestring):
  # taking a empty string
    resultstring = ''
    # Traversee the originalstring
    for element in string:
      # if character is equal to old string then replace it
        if(element == oldstring):
            resultstring += replacestring
        else:
            resultstring += element

    # return the final string
    return resultstring


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

Output:

BTpchGppks

It replaced all instances of the character ‘e’ with the letter ‘p’

Because strings are immutable in Python, we cannot change their contents. As a result, we made a new copy of the string that contained the replaced content.

Method #3:Using Regex

Python includes a regex module (re), which includes a function sub() for replacing the contents of a string based on patterns. We can use the re.sub() function to replace/substitute all occurrences of a character in a string.

Below is the implementation:

import re

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

    # return the final string
    return resultstring


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

Output:

BTpchGppks

In this case, we used the sub() function with the character to be replaced ‘e’ as the first argument and the character ‘p’ as the second argument. The third argument was then passed as the original string.

The Sub() function treated the first argument ‘s’ as a pattern and replaced all matches with the given replacement string, i.e ‘p’. As a result, it replaced all instances of the character ‘e’ with the character ‘p’ .Because strings are immutable in Python, we cannot change their contents. As a result, the regex module’s sub() function returns a copy of the string with the replaced content.
Related Programs:

Python: Replace a Character in a String Read More »

How to Create and Initialize a List of Lists

How to Create and Initialize a List of Lists in Python?

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.

In Python, a list of lists is a list object with each list element being a separate list.

Given the size,

The task is to create and Initialize a list of lists  of given size in Python using different methods.

Examples:

Input :

Size=4

Output :

[ [ ] , [ ] , [ ] , [ ] ]

Creating list of lists with the same ID(Not Preferable):

Below is the fastest way to build and initialize a list of lists with the same ID.

# Let us take size as 4
listoflists = [[]]*4 
# print the listoflists 
print("List of Lists : ", listoflists) 
# Print the ID's of all elements in this listoflists 
print("ID's : ") 
for element in listoflists: 
    print(id(element))

Output:

List of Lists :  [[], [], [], []]
ID's : 
140398466447368
140398466447368
140398466447368
140398466447368

Explanation:

Here List of Lists of size 4 is created but we can see all are having same Id. This will result in the list containing the same list object repeated N times and cause referencing errors.

Creating list of lists with the different ID’s:

It is most preferable because all the lists will have different ID’s such that we can access and refer them separately.

There are several ways to create list of lists some of them are:

Method #1: Using List Comprehension , range() and Append()

Using list comprehensions is the most Pythonic way to build an empty list of lists.

This can be accomplished in the following way:

# Driver code
# let us take size of list as 4
size = 4
# Creating listoflists using list comprehension
listoflists = [[] for i in range(size)]
# Printing empty listoflists
print("List of Lists :", listoflists)

print("ID : ")

# Printing the ID's of all sublists
for element in listoflists:
    print(id(element))

# Initializing list of lists
# let us initialize element in 2 nd sublist
listoflists[1].append(3)

# printing list after initialization
print("List of Lists :", listoflists)

Output:

List of Lists : [[], [], [], []]
ID : 
140259187390280
140259187390024
140259187390088
140259187390152
List of Lists : [[], [3], [], []]

Explanation:

Here we created list of lists of size 4, with different IDs for each sublist.  As a result, we can refer to them and initialise them separately.

We initialized second sublist with element 3.

Method #2 :  Using For loop and Append()

Let’s say we want to make a list that includes 4 separate sub-lists.

To do so, we’ll first construct a new empty list, then use a for loop to iterate from 0 to 3 and add an empty list

to the new list for each iteration.

Below is the implementation:

# Driver code
# let us take size of list as 4
size = 4
# Taking empty listoflists
listoflists = []
# Iterate over a sequence of numbers from 0 to size
for i in range(size):
    listoflists.append([])

# Printing empty listoflists
print("List of Lists :", listoflists)

print("ID : ")

# Printing the ID's of all sublists
for element in listoflists:
    print(id(element))

# Initializing list of lists
# let us initialize element in 2 nd sublist
listoflists[1].append(3)

# printing list after initialization
print("List of Lists :", listoflists)

Output :

List of Lists : [[], [], [], []]
ID : 
140629449111368
140629449111240
140629449111304
140629449111176
List of Lists : [[], [3], [], []]

Method #3: Using Itertools

The repeat() function in the itertools module can be used to replace the range() function in the above list comprehension.

Below is the implementation

# import repeat from itertools
from itertools import repeat
# let us take size of list as 4
size = 4
# Creating listoflists using list comprehension
listoflists = [[] for i in repeat(None, size)]
# Printing empty listoflists
print("List of Lists :", listoflists)

print("ID : ")

# Printing the ID's of all sublists
for element in listoflists:
    print(id(element))

# Initializing list of lists
# let us initialize element in 2 nd sublist
listoflists[1].append(3)

# printing list after initialization
print("List of Lists :", listoflists)

Output:

List of Lists : [[], [], [], []]
ID : 
140551299438408
140551299438152
140551299438216
140551299438280
List of Lists : [[], [3], [], []]

Method #4 : Using empty() in Numpy

The empty() function in the Numpy module in Python creates an empty Numpy array of a given shape

numpy.empty(shape, dtype=float, order='C')

It creates a new Numpy array of the specified shape.
Now, to generate a list of lists, we’ll use the empty() function to create a 2D Numpy array, which we’ll then transform to a list of lists using the numpy.tolist() function.

Below is the implementation:

# importing numpy module
import numpy

# let us take size of list as 4
size = 4

# Create a 2D Numpy array of shape (4, 0) and convert it to list of lists
listoflists = numpy.empty((size, 0)).tolist()

# Printing empty listoflists
print("List of Lists :", listoflists)

print("ID : ")

# Printing the ID's of all sublists

for element in listoflists:
    print(id(element))

# Initializing list of lists

# let us initialize element in 2 nd sublist

listoflists[1].append(3)

# printing list after initialization

print("List of Lists :", listoflists)

Note: This method performance is often slower than the list comprehension.
Related Programs:

How to Create and Initialize a List of Lists in Python? Read More »

How to Check if a Key Exists in Dictionary

Python How to Check if a Key Exists in Dictionary

A Python dictionary is a list of objects that are not in any particular order i.e Unordered.

A dictionary is made up of a collection of key-value pairs. Each key-value pair corresponds to a specific value.

Curly braces { } can be used to describe a dictionary by enclosing a comma-separated list of key-value pairs.

Every key is separated from its associated value by a colon “:”.

Given a dictionary, the task is to determine whether the given key exists in the dictionary.

Examples:

Input :

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

Output:

Yes

Check whether given Key already exists in a Python Dictionary

There are several ways to check whether the given key exists in the dictionary some of them are:

Method #1: Using keys() function

The keys() method returns a list of all the available keys in the dictionary. Using the inbuilt method keys(), use an if statement and the ‘in’ operator to determine whether or not the key exists in the dictionary.

# Given Dictionary

dictionary = {'this': 100, 'is': 200, 'python': 300}

# Given key
key = 'is'

# Checking if key is exist in dictionary using keys() method
if key in dictionary.keys():
  # If the key exits then print yes
    print("Yes")
# If the  key do not exist then print no
else:
    print("No")

Output:

Yes

Method #2: Using if-in Statements

To verify if a key exists in the dictionary, we can use the ‘in operator’ directly with the dictionary.

The expression:

key in dictionary

If the key exists in the dictionary, it will evaluate to True; otherwise, it will evaluate to False.

Let’s use this to see if the key is in the dictionary.

# Given Dictionary

dictionary = {'this': 100, 'is': 200, 'python': 300}

# Given key
key = 'is'

# Using if and in to check whether the key is present in dictionary
if key in dictionary:
  # If the key exits then print yes
    print("Yes")
# If the  key do not exist then print no
else:
    print("No")

Output:

Yes

Method #3: Using List and if statement

  • Convert the dictionary keys to list.
  • Check if the key present in this list using if statement.

Below is the implementation:

# Given Dictionary
dictionary = {'this': 100, 'is': 200, 'python': 300}

# Given key
key = 'is'
# Converting dictionary keys to list
keyslist = list(dictionary.keys())

# Checking if key is exist in list using if
if key in keyslist:
  # If the key exits then print yes
    print("Yes")
# If the  key do not exist then print no
else:
    print("No")

Output:

Yes

Method #4: Using Exceptional Handling

It will raise a KeyError if we try to access a value of key that does not exist in the dictionary. This can also be used to see if anything exists in the dict.

This can also be a way to check if exist in dictionary or not .

Below is the implementation:

# Given Dictionary
dictionary = {'this': 100, 'is': 200, 'python': 300}

# Given key
key = 'is'
# Using try and except
try:
    # If the key exist in dictionary its value is assigned to test and then it prints yes
    test = dictionary[key]
    print("Yes")
# If the key do not exist in dictionary it prints no
except KeyError:
    print("No")

Output:

Yes

Method #5: Using get() function

The dict class in Python has a get() method that accepts a key and a default value.

dictionary.get(keyname, value)

The function’s behaviour,

  • If the given key is found in the dictionary, it returns the value associated with that key.
  • If the given key does not exist in the dictionary, the passed default value argument is returned.
  • If the given key does not exist in the dictionary and the default value is not provided, it returns None.

Below is the implementation:

# Given Dictionary
dictionary = {'this': 100, 'is': 200, 'python': 300}

# Given key
key = 'is'
# Using get()
if dictionary.get(key) is not None:
    print("Yes")
else:
    print("No")

Output:

Yes

Method #6 : Using ‘if not in’ statement

We’ve just verified whether the key exists in the dictionary so far.

However, if we want to verify if a key does not exist in the dictionary, we can use ‘if not in’ with the dictionary directly.

Below is the implementation:

# Given Dictionary
dictionary = {'this': 100, 'is': 200, 'python': 300}

# Given key
key = 'is'
# Using if not in
if key not in dictionary:
  # if the key not in dictionary then we print no
    print("No")
else:
    print("Yes")

Output:

Yes

Related Programs:

Python How to Check if a Key Exists in Dictionary Read More »

Remove Elements from List by Index or Indices

Python: Remove Elements from List by Index or Indices

Lists are ordered sequences that can contain a wide range of object types. Lists can also have duplicate members. Lists in Python can be compared to arrays in other programming languages. But there is one significant difference. Arrays can only contain elements of the same data type, whereas Python lists can contain items of various data types.

Python Lists include a number of methods for removing items from the list.

This article will go over various methods for removing a single or multiple elements from a list.

Examples:

Input:

givenlist=["hello", "this", "is", "Btech", "Geeks"] , index=2

Output:

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

Remove values from the List Using Indexes or Indices

There are several ways to remove elements from the list using Indexes or Indices some of them are:

 

>Method#1: Using del keyword

“del list object [index]” can be used to exclude an item from a list based on its index location.

The del keyword, on the other hand, will raise IndexError if the list is empty or the specified index is out of range.

# Function which removes the element at given index and returns list
def removeIndex(givenlist, index):
    # deleting the index
    del givenlist[index]
    # return the list
    return givenlist

# Driver code


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

Output:

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

It removed the element at position 2 . But what if we try to delete an element with an out-of-range index?

As an example,

we will delete the element at index 10(which doesn’t in this list) the output is:

del givenlist[index]
IndexError: list assignment index out of range

Because the given index was out of bounds, it raised an IndexError. The index position was greater than the

list’s length. To avoid this index error, we should always check to see if the given index is valid.

Below is the implementation:

# Function which removes the element at given index and returns list
def removeIndex(givenlist, index):
    # deleting the index
    if(index < len(givenlist)):
        del givenlist[index]
    # return the list
    return givenlist

# Driver code


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

Output:

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

>Method #2: Using pop() function

The list class in Python has a function pop(index) that removes an item from the list at the given index.

However, if the list is empty or the given index is out of range, the pop() function may throw an IndexError.

As a result, we should exercise caution when using this function to delete an item from a list based on its index position.

We wrote a function that deletes an element from a list based on its index. It uses the pop() function internally,

but first checks to see if the given index is valid. Let us illustrate with an example:

# Function which removes the element at given index and returns list
def removeIndex(givenlist, index):
  # using pop() function
    if index < len(givenlist):
        givenlist.pop(index)
   # returning the list
    return givenlist


# Driver code


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

Output:

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

The function removeIndex() accepts two arguments,

  • A givenlist from which an element must be removed.
  • An index that represents the place in the given list where an element must be removed.

>Method #3: Using slicing

In each of the previous solutions, we changed the list while it was still in place. Slicing, on the other hand, can be used to create a new list by removing the element at a given index from the original list.

To delete an element at index N, for example, divide the list into three parts.

  1. Elements ranging from 0 to N-1
  2. Element at index position N
  3. Elements starting at index position N+1 and continuing to the end of the list.

Below is the implementation:

# Function which removes the element at given index and returns list
def removeIndex(givenlist, index):
  # using slicing
    givenlist = givenlist[:index] + givenlist[index+1:]
  # returning the list
    return givenlist


# Driver code


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

Output:

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

>Method #4 : Using indices to remove multiple elements

Assume we have a list of 7 elements and want to remove the elements at indexes 1, 5, and 6. We can’t just name the pop after iterating over the specified index positions (index). The element at a given index will be removed by the pop() function, and the index location of all elements after the deleted elements will change as a result (decrease by 1).

The best approach is to sort the index positions in decreasing order and then call the pop() function on the highest to lowest index positions. To make this process as simple as possible, we’ve built a function.

Based on the specified index positions, it may remove multiple elements from a list.

# Function which removes the element at given index and returns list
def removeIndex(givenlist, indices):
    # sorting indices list in reverse order
    indices = sorted(indices, reverse=True)
    # Traverse the indices list
    for index in indices:
        if index < len(givenlist):
            givenlist.pop(index)

    # returning the list
    return givenlist


# Driver code
# given list
givenlist = ["hello", "this", "is", "Btech", "Geeks"]
# given indices list which are to be removed
indices = [1, 2, 3]
# passing list and indices list to removeIndex function to remove the element
print(removeIndex(givenlist, indices))

Output:

['hello', 'Geeks']

Related Programs:

Python: Remove Elements from List by Index or Indices Read More »