Python

Create a List of all the Keys in the Dictionary

Python : How to Create a List of all the Keys in the Dictionary ?

Dictionaries are Python’s implementation of an associative list, which may be a arrangement . A dictionary may be a collection of key-value pairs that are stored together. A key and its value are represented by each key-value pair.

Examples:

Input:

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

Output:

['This', 'is', 'BTechGeeks']

Create a List of all keys of a Dictionary

There are several ways to create a list of all keys of a dictionary some of them are:

Method #1:Using keys() +list() function

The dictionary class in Python has a member function called dict.keys ()

It returns a view object or an iterator that iterates through the list of all keys in the dictionary. This object can be used for iteration or to create a new list.

Below is the implementation:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# converting the keys of dictionary using keys() +list() function
keyslist = list(dictionary.keys())
# print the list of keys
print(keyslist)

Output:

['This', 'is', 'BTechGeeks']

Method #2 :Using unpacking (*args)

Unpacking with * works with any iterable object, and because dictionaries return their keys when iterated through, it is simple to create a list by using it within a list literal.

Below is the implementation:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# converting the keys of dictionary using args(*) function
keyslist = [*dictionary]
# print the list of keys
print(keyslist)

Output:

['This', 'is', 'BTechGeeks']

Method #3 :Using List Comprehension

We can convert to list using list comprehension in a single line.

Below is the implementation:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# converting the keys of dictionary using list comprehension
keyslist = [key for key in dictionary]
# print the list of keys
print(keyslist)

Output:

['This', 'is', 'BTechGeeks']

Related Programs:

Python : How to Create a List of all the Keys in the Dictionary ? Read More »

How to Iterate over Nested Dictionary -Dict of Dicts

Python: How to Iterate over Nested Dictionary -Dict of Dicts

Dictionaries are Python’s implementation of an associative list, which may be a arrangement . A dictionary may be a collection of key-value pairs that are stored together. A key and its value are represented by each key-value pair.

To an infinite depth, a dictionary may include another dictionary, which can contain dictionaries, and so on. This is referred to as a nested dictionary.

Nested dictionaries are one among several ways during which structured information is represented (similar to records or structures in other languages).

Examples:

Input:

nesteddict = {
'hello': {'www': 100, 'yyy': 'Helloworld'},
'this': {'www': 'vikram', 'age': 20, 'DOB': 'FEB'},
'BTechGeeks': {'PLACE': 'HYDERABAD', 'PINCODE': 500000,
'PYTHON': {'FUNCTIONS': 'Built in', 'year': 1999}},

Output:

('hello', 'www', 100)
('hello', 'yyy', 'Helloworld')
('this', 'www', 'vikram')
('this', 'age', 20)
('this', 'DOB', 'FEB')
('BTechGeeks', 'PLACE', 'HYDERABAD')
('BTechGeeks', 'PINCODE', 500000)
('BTechGeeks', 'PYTHON', 'FUNCTIONS', 'Built in')
('BTechGeeks', 'PYTHON', 'year', 1999)

Traverse over Nested Dictionary

To get an iterable sequence of all key-value pairs in a normal dictionary, simply call the dictionary’s items() function. A value in a nested dictionary, on the other hand, can be another dictionary object. To accomplish this, we must call the items() function again on such values to obtain another iterable sequence of pairs and then search for dict objects within those pairs as well. Using recursion, we can accomplish all of this in a straightforward manner.

We wrote a function that takes a dictionary as an argument and returns all key-value pairs contained within it. Internal / nested dictionary values were included. It returns a tuple containing all keys for that value in hierarchy for nested structures.

Below is the implementation:

# function which print all the values of nested dictionary
def printNested(nesteddict):
    # Traverse the dictionary
    for key, value in nesteddict.items():
        # If the value is of the dictionary type, then print
        # all of the keys and values within the nested dictionary.
        if isinstance(value, dict):
            for pair in printNested(value):
                yield (key, *pair)
        else:
            yield(key, value)


# given nested_dictionary
nesteddict = {
    'hello':    {'www': 100, 'yyy': 'Helloworld'},
    'this':    {'www': 'vikram', 'age': 20, 'DOB': 'FEB'},
    'BTechGeeks':    {'PLACE': 'HYDERABAD', 'PINCODE': 500000,
                      'PYTHON': {'FUNCTIONS': 'Built in', 'year': 1999}},
}
# passing nested dictionary to printNested Function using loop
for pair in printNested(nesteddict):
    print(pair)

Output:

('hello', 'www', 100)
('hello', 'yyy', 'Helloworld')
('this', 'www', 'vikram')
('this', 'age', 20)
('this', 'DOB', 'FEB')
('BTechGeeks', 'PLACE', 'HYDERABAD')
('BTechGeeks', 'PINCODE', 500000)
('BTechGeeks', 'PYTHON', 'FUNCTIONS', 'Built in')
('BTechGeeks', 'PYTHON', 'year', 1999)

Working of the above function:

We iterated over all the values in a dictionary of dictionaries using the function nested dict pair iterator() and printed each pair, including the parent keys.

We iterated over all the key-value pairs of a given dictionary object within the function, and for each value object in the pair, we checked whether the value is of dict type or not. If not, it just returns the pair, but if value is a dict, it calls itself again with the dict value object as an argument and returns all of its key-value pairs. The process is repeated until all of the internal dictionary objects have not been covered. This is how a dictionary of dictionaries’ key-value pairs are generated.
Related Programs:

Python: How to Iterate over Nested Dictionary -Dict of Dicts Read More »

Print all Key-Value Pairs of a Dictionary

Python: Print all Key-Value Pairs of a Dictionary

Dictionaries are Python’s implementation of an associative list, which may be a arrangement . A dictionary may be a collection of key-value pairs that are stored together. A key and its value are represented by each key-value pair.

Given a dictionary, the task is to print all key and values of the dictionary.

Examples:

Input:

dictionary = {"this": 100, "is": 200, "BTechGeeks": 300}

Output:

This 100
is 200
BTechGeeks 300

Display all Key-value pairs of a Dictionary

There are several ways to traverse the dictionary some of them are:

Method #1: Using for loop (iterating over keys only)

To iterate over all keys in a dictionary, a dictionary object can also be used as an iterable object. As a result, we can use for loop on a dictionary with ease. It loops through all of the keys in the dictionary using for in the dictionary. We will print the value associated with each key.

Below is the implementation:

# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# Using for loop to traverse the dictionary
for key in dictionary:
    # Getting value at key
    value = dictionary[key]
    # printing values and keys
    print(key, value)

Output:

This 100
is 200
BTechGeeks 300

Method #2:Using for loop and items()

The items() function of the dictionary class returns an iterable sequence of all key-value pairs within the dictionary. We can use a for loop to iterate through this list of pairs and print them one by one.

Below is the implementation:

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

# Printing all key-value pairs
for key, value in dictionary.items():
    print(key, value)

Output:

This 100
is 200
BTechGeeks 300

Method #3:Using List Comprehension

Since the items() function of a dictionary returns an iterable sequence of key-value pairs, we may use this list comprehension to iterate over all diction pairs.

Below is the implementation:

# Given dictionary 
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300} 
# Using list comprehension 
[print(key, value) for key, value in dictionary.items()]

Output:

This 100
is 200
BTechGeeks 300
# Given dictionary
dictionary = {'This': 100, 'is': 200, 'BTechGeeks': 300}
# Using items and converting dictionary to list
dictlist = list(dictionary.items())
# traversing in reversed of this list
for key, value in reversed(dictlist):
    print(key, value)

Output:

BTechGeeks 300
is 200
This 100

Related Programs:

Python: Print all Key-Value Pairs of a Dictionary Read More »

IterateLoop over all Nested Dictionary values

Python: Iterate/Loop over all Nested Dictionary values

Dictionaries are Python’s implementation of an associative list, which may be a arrangement . A dictionary may be a collection of key-value pairs that are stored together. A key and its value are represented by each key-value pair.

To an infinite depth, a dictionary may include another dictionary, which can contain dictionaries, and so on. This is referred to as a nested dictionary.

Nested dictionaries are one among several ways during which structured information is represented (similar to records or structures in other languages).

Examples:

Input:

nesteddict = {
'hello': {'www': 100, 'yyy': 'Helloworld'},
'this': {'www': 'vikram', 'age': 20, 'DOB': 'FEB'},
'BTechGeeks': {'PLACE': 'HYDERABAD', 'PINCODE': 500000,
'PYTHON': {'FUNCTIONS': 'Built in', 'year': 1999}},
}

Output:

100
Helloworld
vikram
20
FEB
HYDERABAD
500000
Built in
1999

Traverse over all Nested Dictionary

1)Traverse the values of nested Dictionary

We can only call the values() function of a dictionary for a normal dictionary to get an iterable sequence of values. However, a value can be another dictionary object in a nested dictionary. To do this, we need to call the values() function again and get a new iterative sequence of values and search for dictation objects in those values. This is possible with recurrence in a simple way.

To print all of the values in this dictionary, we wrote a function that will recursively go through the nested dictionary and print all of the values.

Below is the implementation:

# function which print all the values of nested dictionary


def printNested(nesteddict):
    # Traverse the dictionary
    for key, value in nesteddict.items():
        # If the value is of the dictionary type, then print
        # all of the values within the nested dictionary.
        if isinstance(value, dict):
            printNested(value)
        else:
            print(value)


# given nested_dictionary
nesteddict = {
    'hello':    {'www': 100, 'yyy': 'Helloworld'},
    'this':    {'www': 'vikram', 'age': 20, 'DOB': 'FEB'},
    'BTechGeeks':    {'PLACE': 'HYDERABAD', 'PINCODE': 500000,
                      'PYTHON': {'FUNCTIONS': 'Built in', 'year': 1999}},
}
# passing nested dictionary to printNested Function
printNested(nesteddict)

Output:

100
Helloworld
vikram
20
FEB
HYDERABAD
500000
Built in
1999

2)Convert all nested dictionary values to list

We can convert nested dictionary values to list by taking an empty list and appending all values to list as shown below.

Below is the implementation:

# function which print all the values of nested dictionary


def printNested(newlist, nesteddict):
    # Traverse the dictionary
    for key, value in nesteddict.items():
        # If the value is of the dictionary type, then print
        # all of the values within the nested dictionary.
        if isinstance(value, dict):
            printNested(newlist, value)
        else:
            newlist.append(value)
    return newlist


# given nested_dictionary
nesteddict = {
    'hello':    {'www': 100, 'yyy': 'Helloworld'},
    'this':    {'www': 'vikram', 'age': 20, 'DOB': 'FEB'},
    'BTechGeeks':    {'PLACE': 'HYDERABAD', 'PINCODE': 500000,
                      'PYTHON': {'FUNCTIONS': 'Built in', 'year': 1999}},
}
newlist = []
# passing nested dictionary to printNested Function
print(printNested(newlist, nesteddict))

Output:

[100, 'Helloworld', 'vikram', 20, 'FEB', 'HYDERABAD', 500000, 'Built in', 1999]

Related Programs:

Python: Iterate/Loop over all Nested Dictionary values Read More »

Check if Dictionary is Empty

Python: Check if Dictionary is Empty

Dictionaries are Python’s implementation of an associative list, which is a data structure. A dictionary is a collection of key-value pairs that are stored together. A key and its value are represented by each key-value pair.

Examples:

Input:

dictionary = {"this": 100, "is": 200, "BTechGeeks": 300}

Output:

Dictionary is not empty

Input:

dictionary= { }

Output:

Dictionary is empty

Given a dictionary, the task is check if dictionary is empty or not.

Check if Dictionary is Empty

There are 2 ways to check if the dictionary is empty they are:

Method #1: Using if operator

A dictionary can be cast or converted to a bool variable in Python. If the dictionary is empty, it will be True; otherwise, it will be False.

We can now apply this concept by directly inserting a dictionary object into the if statement. If we pass the dictionary object into the if statement, it will be implicitly converted to a bool value. If the dictionary is empty, it returns True otherwise, it returns False.

Below is the implementation:

Example-1:

# given dictionary
dictionary = {"this": 100, "is": 200, "BTechGeeks": 300}

# checking if dictionary  is empty
if dictionary:
    print("Dictionary is not empty")
else:
    print("Dictionary is empty")

Output:

Dictionary is not empty

Example-2:

# given dictionary
dictionary = {}

# checking if dictionary  is empty
if dictionary:
    print("Dictionary is not empty")
else:
    print("Dictionary is empty")

Output:

Dictionary is empty

Method #2:Using len() function

When we pass the dictionary object to the len() function, we get the number of key-value pairs in the dictionary. So, we can use the len() function to determine whether or not the dictionary is empty.

If the length of dictionary is 0 then dictionary is empty otherwise not.

Below is the implementation:

Example -1:

# given dictionary
dictionary = {"this": 100, "is": 200, "BTechGeeks": 300}

# checking if dictionary  is empty using len() function
if len(dictionary) == 0:
    print("Dictionary is empty")
else:
    print("Dictionary is not empty")

Output:

Dictionary is not empty

Example-2:

# given dictionary
dictionary = {}

# checking if dictionary  is empty using len() function
if len(dictionary) == 0:
    print("Dictionary is empty")
else:
    print("Dictionary is not empty")

Output:

Dictionary is empty

Related Programs:

Python: Check if Dictionary is Empty Read More »

Iterate over dictionary with list values

Python: Iterate over Dictionary with List Values

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.

Given a dictionary with the values as list, the task is to iterate over the dictionary and print it.

Examples:

Input:

dictionary = {
'hello': [110, 200, 300],
'this': [3, 4, 5],
'is': 10,
'BTechGeeks': [1, 2, 3, 'python']
}

Output:

hello : 110 200 300 
this : 3 4 5 
is : 10 
BTechGeeks : 1 2 3 python

Traverse the dictionary with list values

We can traverse the dictionary by many ways two of them are

Method #1:Using nested for loop and exceptional handling

Approach:

  • Iterate over the keys of dictionary.
  • Now using nested for loop iterate over the values of keys.
  • If a key has only one value, we get an error, so handle those errors with exceptional handling in Python by printing the key’s single value.

Below is the implementation:

# given dictionary
dictionary = {
    'hello': [110, 200, 300],
    'this': [3, 4, 5],
    'is': 10,
    'BTechGeeks': [1, 2, 3, 'python']
}
# iterate through dictionary
for key in dictionary:
    print(key, end=" : ")
    try:
        for value in dictionary[key]:
            print(value, end=" ")
    except:
        print(dictionary[key], end=" ")
    print()

Output:

hello : 110 200 300 
this : 3 4 5 
is : 10 
BTechGeeks : 1 2 3 python

Method #2:Using List comprehension

In the preceding example, we iterated through all of the list values for each key. However, if you want a complete list of pairs, we can also use list comprehension. Because a key in our dictionary can have multiple values, for each pair we will generate a list of pairs where the key is the same but the value is different.

Below is the implementation:

# given dictionary
dictionary = {
    'hello': [110, 200, 300],
    'this': [3, 4, 5],
    'is': [2, 10, 45],
    'BTechGeeks': [1, 2, 3, 'python']
}
# using list comprehension
keyvaluepairs = [(key, value)
                 for key, values in dictionary.items()
                 for value in values]
# traverse and print key  value pairs
for i in keyvaluepairs:
    print(i)

Output:

('hello', 110)
('hello', 200)
('hello', 300)
('this', 3)
('this', 4)
('this', 5)
('is', 2)
('is', 10)
('is', 45)
('BTechGeeks', 1)
('BTechGeeks', 2)
('BTechGeeks', 3)
('BTechGeeks', 'python')

Related Programs:

Python: Iterate over Dictionary with List Values Read More »

Python Pandas : How to drop rows in DataFrame by index labels

How to drop rows in DataFrame by index labels in Python ?

In this article we are going to learn how to delete single or multiple rows from a Dataframe.

For this we are going to use the drop( ) function.

Syntax - DataFrame.drop( labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise' )

Where, the function accepts name/series of names in the label and deletes the rows or columns it points to. The axis is used to alter between rows and columns, 0 means rows and 1 means columns(default value is 0).

Also we have to pass inplace = True if we want the modified values to be updated in our dataframe object, as the drop( ) function returns the modified values into a new Dataframe object. To explain this properly we will be using inplace = True in all our programs.

We are going to use the following dataset as example

      Name          Age       Location       Country
a     Jill               16         Tokyo             Japan
b    Phoebe        38        New York        USA
c     Kirti             39         New York        USA
d     Veena         40         Delhi               India
e     John           54          Mumbai         India
f     Michael       21         Tokyo              Japan

Deleting a single Row in DataFrame by Row Index Label :

To delete a single row by the label we can just pass the label into the function.

Here let’s try to delete‘b’ row.

#program :

import numpy as np
import pandas as pd

#Examole data
students = [('Jill',   16,  'Tokyo',     'Japan'),
('Phoebe', 38,  'New York',  'USA'),
('Kirti',  39,  'New York',  'USA'),
('Veena',  40,  'Delhi',     'India'),
('John',   54,  'Mumbai',    'India'),
("Michael",21,  'Tokyo',     'Japan')]

#Creating an object of dataframe class
dfObj = pd.DataFrame(students, columns = ['Name' , 'Age', 'Location' , 'Country'], index=['a', 'b', 'c' , 'd' , 'e' , 'f'])
#Deleting 'b' row
dfObj.drop('b',inplace=True)
print(dfObj)

Output :

        Name     Age      Location       Country
a        Jill          16       Tokyo            Japan
c        Kirti        39       New York      USA
d      Veena      40       Delhi             India
e      John         54       Mumbai        India
f     Michael     21       Tokyo            Japan

Deleting Multiple Rows in DataFrame by Index Labels :

To delete multiple rows by their labels we can just pass the labels into the function inside a square bracket [ ].

Here let’s try to delete 'a' and 'b' row.

#program :

import numpy as np
import pandas as pd

#Examole data
students = [('Jill',   16,  'Tokyo',     'Japan'),
('Phoebe', 38,  'New York',  'USA'),
('Kirti',  39,  'New York',  'USA'),
('Veena',  40,  'Delhi',     'India'),
('John',   54,  'Mumbai',    'India'),
("Michael",21,  'Tokyo',     'Japan')]

#Creating an object of dataframe class
dfObj = pd.DataFrame(students, columns = ['Name' , 'Age', 'Location' , 'Country'], index=['a', 'b', 'c' , 'd' , 'e' , 'f'])

#Deleting 'a' and 'b' row
dfObj.drop(['a','b'],inplace=True)
print(dfObj)
Output :
      Name       Age     Location       Country
c     Kirti          39      New York      USA
d     Veena      40      Delhi             India
e     John         54     Mumbai         India
f     Michael     21     Tokyo             Japan

Deleting Multiple Rows by Index Position in DataFrame :

To delete multiple rows we know the index position, however, the function drop( ) doesn’t take indices as parameters. So we create the list of labels and pass them into the drop( ) function. Let’s try deleting the same rows again but by index.

#program :

import numpy as np
import pandas as pd

#Examole data
students = [('Jill',   16,  'Tokyo',     'Japan'),
('Phoebe', 38,  'New York',  'USA'),
('Kirti',  39,  'New York',  'USA'),
('Veena',  40,  'Delhi',     'India'),
('John',   54,  'Mumbai',    'India'),
("Michael",21,  'Tokyo',     'Japan')]

#Creating an object of dataframe class
dfObj = pd.DataFrame(students, columns = ['Name' , 'Age', 'Location' , 'Country'], index=['a', 'b', 'c' , 'd' , 'e' , 'f'])

#Deleting 1st and 2nd row
dfObj.drop([dfObj.index[0] , dfObj.index[1]],inplace=True)
print(dfObj)
Output :
      Name      Age     Location     Country
c     Kirti          39     New York     USA
d     Veena      40     Delhi            India
e     John         54    Mumbai        India
f     Michael     21     Tokyo          Japan

Want to expert in the python programming language? Exploring Python Data Analysis using Pandas tutorial changes your knowledge from basic to advance level in python concepts.

Read more Articles on Python Data Analysis Using Padas – Remove Contents from a Dataframe

Python Pandas : How to drop rows in DataFrame by index labels Read More »

Python Tuple : Append , Insert , Modify & delete elements in Tuple

How to append, insert, modify and delete elements in Tuple in Python ?

This article is about how we can append, insert, modify and delete elements in Tuple.

As we know a tuple in Python stores ordered and immutable objects. It is one of data type which stores multiple items in a single variable where all the elements are placed inside parentheses () and separated by commas.

Syntax : sample_tuple = (element1, element2, element3, ...)

As tuple is immutable so once created values can not be changed. Still if we want to modify the existing tuple, then in that case we have to create a new tuple with updated elements only from the existing tuple. So let’s start exploring the topic to know how we can append, insert, modify and delete elements in Tuple.

Append an element in Tuple at end :

If we have a tuple and to append an element into it , then we will create copy of the existing tuple first then we will append the new element by using + operator.

So , let’s see the implementation of it.

#Program :

# A tuple created
tuple_Obj = (1 , 3, 4, 2, 5 )

#printing old tuple
print("Old tuple is :")
print(tuple_Obj)

# Appending 9 at the end of tuple
tuple_Obj = tuple_Obj + (9 ,)

#printing new tuple
print("After appending new tuple is :")
print(tuple_Obj)
Output  :
Old tuple is :
(1 , 3, 4, 2, 5 )
After appending new tuple is :
(1 , 3, 4, 2, 5, 9 )

Insert an element at specific position in tuple :

If we want to insert a specific element at particular index, then we have to create a new tuple by slicing the existing tuple and copying elements of old tuple from it.

Suppose we have to insert at index n then we have to create two sliced copies of existing tuple from (0 to n) and (n to end). Like

# containing elements from 0 to n-1 
tuple_Obj [ : n] 
# containing elements from n to end 
tuple_Obj [n : ]

So, let’s see the implementation of it.

#Program :

# A tuple created
tuple_Obj = (1 , 3, 4, 2, 5 )

#printing old tuple
print("Old tuple is :")
print(tuple_Obj)

n = 2
# Insert 9 in tuple at index 2
tuple_Obj = tuple_Obj[ : n ] + (9 ,) + tuple_Obj[n : ]

#printing new tuple
print("After appending new tuple is :")
print(tuple_Obj)
Output  :
Old tuple is :
(1 , 3, 4, 2, 5 )
After appending new tuple is :
(1 , 3, 9, 4, 2, 5 )

Modify / Replace the element at specific index in tuple :

If we want to replace the element at index n in tuple then we have to use the same slicing logic as we used in the above example, But in this we have to slice the tuple from from (0 to n-1) and (n+1 to end) , as we will replace the element at index n, so after replacing we are copying the elements again from n+1 index of the old tuple.

So, let’s see the implementation of it.

#Program :

# A tuple created
tuple_Obj = (1 , 3, 4, 2, 5 )

#printing old tuple
print("Old tuple is :")
print(tuple_Obj)

n = 2
# Insert 'program' in tuple at index 2
tuple_Obj = tuple_Obj[ : n] + ('program' ,) + tuple_Obj[n + 1 : ]

#printing new tuple
print("After appending new tuple is :")
print(tuple_Obj)
Output :
Old tuple is : 
(1 , 3, 4, 2, 5 ) 
After appending new tuple is : 
(1 , 3, 'program', 2, 5 )

Delete an element at specific index in tuple :

If we want to delete an element at index n in tuple then we have to use the same slicing logic as  we used in the above example, means we will slice the tuple from from (0 to n-1) and (n+1 to end) , like

# containing elements from 0 to n-1 
tuple_Obj [ : n] 
# containing elements from n to end 
tuple_Obj [n+1 : ]

So, let’s see the implementation of it.

#Program :

# A tuple created
tuple_Obj = (1 ,3, 'program', 4, 2, 5 )

#printing old tuple
print("Old tuple is :")
print(tuple_Obj)

n = 2
# Deleting the element at index 2 
tuple_Obj = tuple_Obj[ : n ] + tuple_Obj[n+1 : ]

#printing new tuple
print("After appending new tuple is :")
print(tuple_Obj)
Output : 
Old tuple is : (1 , 3, 'program',  4, 2, 5 ) 
After appending new tuple is : (1 , 3, 4, 2, 5 )

Python Tuple : Append , Insert , Modify & delete elements in Tuple Read More »

Python : filter() function | Tutorial and Examples

filter() function in Python

This article is about using filter() with lambda.

filter() function :

This filter() function is used to filter some content from a given sequence where the sequence may be a list, tuple or string etc.

Syntax : filter(function, iterable)

where,

  • function refers to a function that accepts an argument and returns bool i.e True or False based on some condition.
  • iterable refers to the sequence which will be filtered.

How it works ?

Actually filter() function iterates over all elemnts of the sequence and for each element the given callback function is called.

  • If False is returned by the function then that element is skipped.
  • If True is returned by the function then that element is added into a new list.

Filter a list of strings in Python using filter() :

#Program :

# A list containg string as elemnt
words = ['ant', 'bat', 'dog', 'eye', 'ink', 'job']

# function that filters words that begin with vowel
def filter_vowels(words):
    vowels = ['ant', 'eye', 'ink']

    if(words in vowels):
      return True
    else:
      return False

filtered_vowels = filter(filter_vowels, words)


# Print words that start with vowel
print('The filtered words are:')
for vowel in filtered_vowels:
print(vowel)
Output :
ant
eye
ink

In the above example we had created one separate function as filtered_vowels and we passed it to filter() function.

Using filter() with Lambda function :

In this we will pass an lambda function rather passing a separate function in filter() function. And the condition is to select words whose length is 6.

So, let’s see an example of it.

#Program :

# A list containg string as elemnt
words = ['ant', 'basket', 'dog', 'table', 'ink', 'school']

#It will return string whose length is 6
filtered_vowels = list(filter(lambda x : len(x) == 6 , words))


# Print words that start with vowel
print('The filtered words are:')
for vowel in filtered_vowels:
    print(vowel)
Output :
The filtered words are:
basket
school

Filter characters from a string in Python using filter() :

Now, let’s take example how to filter a character in a string and remove that character in the string.

#Program :

# A list containg string as elemnt
str_sample = "Hello, you are studying from Btech Geeks."

#It will return particular character in the string
#then those chharacters are removed from the string
filteredChars = ''.join((filter(lambda x: x not in ['e', 's'], str_sample)))


# Print the new string 
print('Filtered Characters  : ', filteredChars)
Output : 
Hllo, you ar tudying from Btch Gk.

Filter an array in Python using filter() :

Suppose we have an array. So, let’s see it how we can filter the elements from an array.

#Program :

# Two arrays 
sample_array1 = [1,3,4,5,21,33,45,66,77,88,99,5,3,32,55,66,77,22,3,4,5]
sample_array2 = [5,3,66]

#It will return a new array
#It will filter
#if array2 elemnts are present in array1 then that element will not be removed
filtered_Array = list(filter(lambda x : x not in sample_array2, sample_array1))
print('Filtered Array  : ', filtered_Array)
Output :

[1, 4, 21, 33, 45, 77, 88, 99, 32, 55, 77, 22 ,4]

Python : filter() function | Tutorial and Examples Read More »

Python : How to Compare Strings ? | Ignore case | regex | is vs == operator

How to Compare Strings ? | Ignore case | regex | is vs == operator in Python ?

In this article we will discuss various ways to compare strings in python.

Python provides various operators for comparing strings i.e less than(<), greater than(>), less than or equal to(<=), greater than or equal to(>=), not equal(!=), etc and whenever they are used they return Boolean values i.e True or False.

Compare strings using == operator to check if they are equal using python :

Let’s see it with an example:

#program :

firststr = 'First'
secondstr = 'second'

if firststr == secondstr:
    print('Strings are same')
else:
    print('Strings are not same')
Output:
Strings are not same

As the content of both the string are not same so it returned False.

#Program :

firststr = 'done'
secondstr = 'done'

if firststr == secondstr:
    print('Strings are same')
else:
    print('Strings are not same')
Output:
Strings are same

Here, as the content of both the string are not same so it returned True.

Compare strings by ignoring case using python :

Let’s see it with an example:

#program :

firststr = 'PROGRAM'
secondstr = 'program'

if firststr.lower() == secondstr.lower():
    print('Strings are same')
else:
    print('Strings are not same')
Output :
Strings are same

As we can see that both the strings are same but are in different case. Now let’s try with another operator.

Check if string are not equal using != operator using python :

Let’s see it with an example:

#Program :

firststr = 'python'
secondstr = 'program'

if firststr != secondstr:   
  print('Strings are not same')
else:   
  print('Strings are same')
Output: 
Strings are not same

Here, the two strings are not same so it returned True.

Let’s try some other operators.

Check if one string is less than or greater than the other string :

Let’s see it with an example:

#Program :

if 45 > 29:
    print('"45" is greater than "29"')
if "abc" > "abb":
    print('"abc" is greater than "abb"')
if "ABC" < "abc":
    print('"ABC" is less than "abc"')
if 32 >= 32:
    print('Both are equal')
if 62 <= 65:
    print('"62" is less than 65')
Output :
"45" is greater than "29"
"abc" is greater than "abb"
"ABC" is less than "abc"
Both are equal
"62" is less than 65

Comparing strings : is vs == operator :

Python has the two comparison operator == and is. At first sight they seem to be the same, but actually they are not.

== compares two variable based on their actual value but is operator compares two variables based on the object id and returns True if the two variables refer to the same object and returns False if two variables refer to the different object.

Sometimes is operator is also used to compare strings to check if they are equal or not.

Compare contents using is operator :

Example-1

#Program :

a = 5
b = 5
if a is b:
 print("they are same")
print('id of "a"',id(a))
print('id of "b"',id(b))
Output :
they are same
id of "a" 140710783821728
id of "b" 140710783821728

Example 2:

#Program :

a = "python"
b = "program"
if a is b:
  print("they are same")
else:
  print("they are not same")

print('id of "a"',id(a))
print('id of "b"',id(b))
Output:
they are not same
id of "a" 2104787270768
id of "b" 2104783497712

Compare contents using == operator :

The == operator compares the value or equality of two objects.

#Program :

a = 5
b = 5

if a == b:
  print('Both are same')
Output:

Both are same

Compare strings using regex in python :

A regular expression(re)  or regex is a special text string used for describing a search pattern. We can use that to compare strings.

#program :


import re
repattern = re.compile("88.*")
#list of numbers
List = ["88.3","88.8","87.1","88.0","28.2"]

#check if strings in list matches the regex pattern
for n in List:
 match = repattern.fullmatch(n)
 if match:
  print('string',n ,'matched')
 else:
  print('string',n ,'do not matched')
Output :
string 88.3 matched
string 88.8 matched
string 87.1 do not matched
string 88.0 matched
string 28.2 do not matched

Python : How to Compare Strings ? | Ignore case | regex | is vs == operator Read More »