Author name: Vikram Chiluka

Count Uppercase Characters in a String

Python: Count Uppercase Characters in a 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.

In this article we are going to count the uppercase letters in the given string

Examples:

Input:

string = "BTechGeeks"

Output:

The given string contains 3 uppercase letters

Count Uppercase Characters in a String

There are several ways to count uppercase letters in the given string some of them are:

Method #1:Using sum() + isupper() function

Using a generator expression, we can iterate over all of the characters in a string. If an uppercase character is discovered during iteration, pass it to the sum() function. Finally, the sum() function returns the total number of uppercase characters in a string.

Below is the implementation:

# given string
string = "BTechGeeks"
# counting uppercase letters in the given string
upper_count = sum(1 for element in string if element.isupper())
# print the count of uppercase letters
print("The given string contains", upper_count, "uppercase letters")

Output:

The given string contains 3 uppercase letters

Method #2:Using for loop

Using a for loop, we can iterate over a string character by character, counting the number of uppercase characters in the string as we go.

Below is the implementation:

# given string
string = "BTechGeeks"
# counting uppercase letters in the given string
upper_count = 0
# traverse the string using for loop
for element in string:
    # checking if the character is in uppercase
    if element.isupper():
      # increase the count if the given letter is upper
        upper_count += 1
# print the count of uppercase letters
print("The given string contains", upper_count, "uppercase letters")

Output:

The given string contains 3 uppercase letters

Method #3:Using List Comprehension

Iterate over all the characters in a string using list comprehension to create a list of only uppercase characters from the string. Then, by obtaining the size of that uppercase character list, we can obtain the number of uppercase characters in the string.

Below is the implementation:

# given string
string = "BTechGeeks"
# counting uppercase letters in the given string using list comprehension
upper_count = len([element for element in string if element.isupper()])
# print the count of uppercase letters
print("The given string contains", upper_count, "uppercase letters")

Output:

The given string contains 3 uppercase letters

Method #4:Using regex

With a pattern that matches all uppercase characters in the string, we can use Python’s regex module’s findall() method. findall() returns a list of all matches in the string, which in our case will be upper case characters. Then, by retrieving the size of that uppercase character list, we can calculate the number of uppercase characters in the string.

Below is the implementation:

import re
# given string
string = "BTechGeeks"
# counting uppercase letters in the given string using regex
upper_count = len(re.findall(r'[A-Z]', string))
# print the count of uppercase letters
print("The given string contains", upper_count, "uppercase letters")

Output:

The given string contains 3 uppercase letters

Related Programs:

Python: Count Uppercase Characters in a String Read More »

Check if all Elements in a List are None

Check if all Elements in a List are None in Python

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 check if all elements in a list are none or not.

Examples:

Input:

givenlist = [None, None, None, None, None, None]

Output:

The givenlist's elements are all None

Check if all items in a list are none in python

There are several ways to check if all items in a list are none some of them are:

Method #1:Using for loop

Iterate through all of the items in a list using a for loop, checking if each item is None or not. Break the loop as soon as a non None object is identified, as this indicates that all items in the list are not None. If the loop ends without finding even a single non-None object, it proves that the list’s items are all None.

Let’s make a function that takes a list and checks whether any of the things are none or not using the logic described above.

Below is the implementation:

# function which checks if all the elements are none in the list are none
def checkNone(givenlist):
    # initializing result to true
    res = True
    # traversing the givenlist
    for element in givenlist:
        if element is not None:
          # all the elements are not null hence return false
            return False
    # if all the elements are null then return the result i.e true
    return res


# driver code
# given list
givenlist = [None, None, None, None, None, None]
# passing givenlist to checkNone function
answer = checkNone(givenlist)
if(answer):
    print("The givenlist's elements are all None")
else:
    print("givenlist elements are not null")

Output:

The givenlist's elements are all None

Method #2:Writing custom function

Create a generic function that checks whether all items in a list are the same and also matches the specified element.

As an argument, this function takes a list and an object. Then, using the same logic as the previous example, determines if all items in the given list match the given object. This feature can be used to see if any of the things in a list are None.

Below is the implementation:

# function which checks if all the elements are none in the list are none
def checkNone(givenlist, value):
    # initializing result to true
    res = True
    # traversing the givenlist
    for element in givenlist:
        if element != value:
          # all the elements are not null hence return false
            return False
    # if all the elements are null then return the result i.e true
    return res


# driver code
# given list
givenlist = [None, None, None, None, None, None]
# passing givenlist to checkNone function
answer = checkNone(givenlist, None)
if(answer):
    print("The givenlist's elements are all None")
else:
    print("givenlist elements are not null")

Output:

The givenlist's elements are all None

Method #3:Using List Comprehension

We generated a Boolean list from the current list using list comprehension. Each element in this bool list corresponds to an item in the main list. Basically, in List Comprehension, we iterated through the given list, checking if each member was None or not. If it’s None, put True in the bool list; otherwise, put False. All() was used to see whether the bool list contained only True or not. If the all() function returns True, our main list only contains None.

Below is the implementation:

# function which checks if all the elements are none in the list are none
def checkNone(givenlist, value):
    # all() +list comprehension  function
    return all([element == value for element in givenlist])


# driver code
# given list
givenlist = [None, None, None, None, None, None]
# passing givenlist to checkNone function
answer = checkNone(givenlist, None)
if(answer):
    print("The givenlist's elements are all None")
else:
    print("givenlist elements are not null")

Output:

The givenlist's elements are all None

Method #4:Using count() function

Using the count() function, we can count the number of none values in the list.

Return True if the count of none values equals the length of the list, otherwise False.

Below is the implementation:

# function which checks if all the elements are none in the list are none
def checkNone(givenlist):
    # using count function
    # counting none values in list
    countnone = givenlist.count(None)
    # return true if count is equal to length
    return countnone == len(givenlist)


# driver code
# given list
givenlist = [None, None, None, None, None, None]
# passing givenlist to checkNone function
answer = checkNone(givenlist)
if(answer):
    print("The givenlist's elements are all None")
else:
    print("givenlist elements are not null")

Output:

The givenlist's elements are all None

Related Programs:

Check if all Elements in a List are None in Python Read More »

Pretty print nested dictionaries – dict of dicts

Python: Pretty Print Nested Dictionaries – 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).

In this article, we’ll look at how to print a nested dictionary in a visually beautiful and readable format.

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,
        "yyy": "Helloworld"
    },
    "this": {
        "www": "vikram",
        "age": 20,
        "DOB": "FEB"
    },
    "BTechGeeks": {
        "PLACE": "HYDERABAD",
        "PINCODE": 500000,
        "PYTHON": {
            "FUNCTIONS": "Built in",
            "year": 1999
        }
    }
}

Print nested dictionaries in pretty way

There are several ways to print nested dictionaries in pretty way some of them are:

1)Using generic function

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 key-values in this dictionary, we wrote a function that will recursively go through the nested dictionary and print all of the key-values.

Below is the implementation:

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 key and values within the nested dictionary.
        if isinstance(value, dict):
            print(key, "  : {\n")
            printNested(value)
            print("\n}\n")

        else:
            print("\t", 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
printNested(nesteddict)

Output:

hello   : {

	 www  :  100
	 yyy  :  Helloworld

}

this   : {

	 www  :  vikram
	 age  :  20
	 DOB  :  FEB

}

BTechGeeks   : {

	 PLACE  :  HYDERABAD
	 PINCODE  :  500000
PYTHON   : {

	 FUNCTIONS  :  Built in
	 year  :  1999

}
}

2)Using json module

Rather than writing our own functions, we can use the json module to print a dictionary of dictionaries in a format that looks like json.

Below is the implementation:

import json as json
# 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}},
}
# using json to print the nested dict
print(json.dumps(nesteddict, indent=4))

Output:

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

3)Using pandas to print as table

We can print the nested dictionary a table using the pandas module.

Below is the implementation:

import pandas as pd
# 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}},
}
print(pd.DataFrame(nesteddict).T)

Output:

                         DOB            PINCODE      PLACE        ...     age      www       yyy
hello                 NaN            NaN              NaN           ...     NaN    100         Helloworld
this                   FEB              NaN              NaN           ...     20        vikram    NaN
BTechGeeks      NaN            500000         HYDERABAD ... NaN      NaN        NaN

[3 rows x 7 columns]

 

 
Related Programs:

Python: Pretty Print Nested Dictionaries – Dict of Dicts Read More »

Print all Values of a Dictionary

Python: Print all Values of a Dictionary

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.

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

Examples:

Input:

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

Output:

200
100
300

Display all values of the Dictionary

There are several ways to display all the values of the dictionary some of them are:

Method #1:Using for loop and values() function

The dictionary class in Python has a function dict.values() that returns an iterable sequence of dictionary values. We can iterate over the sequence of values returned by the function values() using a for loop, and we can print each value while iterating.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# Traverse the dictionary using for loop
for value in dictionary.values():
    # print the values
    print(value)

Output:

200
100
300

Method #2:Converting values to list

The sequence returned by the values() function can be passed to the list to create a list of all values in the dictionary .

We use list() function to achieve this. Print the list(values)

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# converting values to list
valueslist = list(dictionary.values())
# print the values list
for value in valueslist:
    print(value)

Output:

200
100
300

Method #3:Using  list Comprehension

We can also use this list comprehension to iterate through all of the dictionary’s values and print each one individually.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# using list comprehension
print([value for value in dictionary.values()])

Output:

[200, 100, 300]

Related Programs:

Python: Print all Values of a Dictionary Read More »

Check if all Elements in a List are Same or Matches a Condition

Python : Check if all Elements in a List are Same or Matches a Condition

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.

Example:

Input:

givenlist = ['BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks', 'BTechGeeks', ]

Output:

All the elements are equal

Given a list, the task is to check if all elements in a list are same or matches the given condition

Check that all items in a list are identical

There are several ways to check if all elements in a list are same or matches a condition some of them are:

Method #1:Using all() function

any():

If any of the items is True, this function returns True. If the array is empty or all of the values are false, it returns False. Any can be thought of as a series of OR operations on the iterables provided.

Let’s convert the list to Iterable and check that each iterable entry is the same as the first list element using all ()

Below is the implementation:

# given list
givenlist = ['BTechGeeks', 'BTechGeeks',
             'BTechGeeks', 'BTechGeeks', 'BTechGeeks', ]
# checking if all the elements are equal using all() function
if(any(element == givenlist[0] for element in givenlist)):
    print("All the elements are equal")
else:
    print("All the elements are not equal")

Output:

All the elements are equal

Method #2:Using set()

  • Set includes only single elements.
  • Convert the list to set and check whether the length of the set is 1.
  • If the length of given set is 1 the print all the elements are equal
  • else print all the elements are not equal

Below is the implementation:

# given list
givenlist = ['BTechGeeks', 'BTechGeeks',
             'BTechGeeks', 'BTechGeeks', 'BTechGeeks', ]
# converting given list to set
setlist = set(givenlist)
# if the length of given set is 1 then print all the elements are equal
if(len(setlist) == 1):
    print("All the elements are equal")
else:
    print("All the elements are not equal")

Output:

All the elements are equal

Method #3:Using count() function

Count() returns to the list the number of times the item is appeared.

Let’s call the list’s count() function with the first element as an argument. If the number of times it appears in the list equals the length of the list, it means that all of the elements in the list are the same.

Below is the implementation:

# given list
givenlist = ['BTechGeeks', 'BTechGeeks',
             'BTechGeeks', 'BTechGeeks', 'BTechGeeks', ]
# using count function
if(givenlist.count(givenlist[0]) == len(givenlist)):
    print("All the elements are equal")
else:
    print("All the elements are not equal")

Output:

All the elements are equal

Related Programs:

Python : Check if all Elements in a List are Same or Matches a Condition Read More »

Convert Dictionary Values to a List in Python

Convert Dictionary Values to a List in Python

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, the task is to convert values of this dictionary to a list.

Examples:

Example 1:

Input:

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

Output:

[200, 100, 300]

Example 2:

Input:

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

Output:

[200, 100, 300,400]

Convert Dictionary Values to a List in Python

There are several ways to convert dictionary values to a list some of them are:

Method #1:Using list() function

A dictionary class in Python has a function values() that returns an iterable sequence of all dictionary values. The list() function will return a list containing all of the dictionary’s values if we transfer this iterable sequence(dict values) to it.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# converting values to list
valueslist = list(dictionary.values())
# print the values list
for value in valueslist:
    print(value)

Output:

[200, 100, 300]

Method #2:Using List Comprehension

We can also use this list comprehension to iterate over the values of dictionary and convert to list.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# converting values to list using list comprehension
valueslist = ([value for value in dictionary.values()])
# print the values list
print(valueslist)

Output:

[200, 100, 300]

Method #3:Convert specific values of dictionary to list

Assume we want to convert only a selected values in a dictionary to a list.

As an example, consider converting values greater than 100.

We can accomplish this by iterating through the dictionary values and checking the condition.

Below is the implementation:

# Given dictionary
dictionary = {'this': 200, 'is': 100, 'BTechGeeks': 300}
# Traverse the dictionary values and check condition
valueslist = [value for value in dictionary.values() if value > 100]
# print the values list
print(valueslist)

Output:

[200, 300]

 
Related Programs:

Convert Dictionary Values to a List in Python Read More »

Python Continue keyword in Loops

Python : Continue keyword in Loops

To manage looping specifications, the Python programming language contains the following types of loops. The loops can be executed in three different ways in Python. Although all of the methods have similar basic features, they vary in syntax and the time it takes to search for conditions.

For loops:

In Python, the for loop is used to iterate over a list, tuple, or string, or other iterable properties. Traversal is the process of iterating over a sequence.

While loops:

While Loops are used in Python to execute a set of statements over and over until a condition is met.. When the condition is met, the line immediately following the loop in the programme is executed. Indefinite iteration is demonstrated by the while loop. The term “indefinite iteration” refers to the fact that the number of times the loop is executed is not specified explicitly in advance.

Continue keyword in Python Loops

1)Continue keyword

In Python, loops are used to simplify and repeat tasks in an effective manner. However, there can be occasions when you want to completely exit the loop, miss an iteration, or ignore the condition. Loop control statements can be used to do this. Control statements in loops alter the execution sequence.

Like the break comment, continue is a loop control statement. The continue statement is the polar opposite of the break statement in that it pushes the loop to perform the next iteration rather than ending it.
The continue argument, as its name implies, forces the loop to continue or perform the next iteration. When the continue statement is used in a loop, the code within the loop that follows the continue statement is skipped, and the loop’s next iteration begins.

2)Continue keyword in While loop

The control will jump back to the beginning of the while loop if the continue keyword is used within the loop. For that iteration, all lines following the continue keyword will be skipped.

Consider the following scenario: we want to print all numbers from 1 to n that are not divisible by 5.

Below is the implementation:

# given n
n = 16
# let us take a temp variable to 0 as we need to print all numbers from 1 to n
temp = 0
while(temp < n):
    # increment the temp
    temp += 1
    # if the temp is divisible by 5 then use continue
    # As a result, the number will not be printed.
    if(temp % 5 == 0):
        continue
    else:
        print(temp)

Output:

1
2
3
4
6
7
8
9
11
12
13
14
16

Explanation:

We are printing numbers from 1 to n in this while loop. However, within the loop body, we have a check that says if temp is divisible by 5 we should execute the continue keyword.

As a result, when the value of temp is divisible by 5, the continue statement is executed. It returns control to the beginning of the loop and skips the print statement at the end of the loop body.

3)Continue keyword in For loop

Let the implement the above code using for loop.

Below is the implementation:

# given n
n = 16
# using for loop
for temp in range(1, n+1):
    # if the temp is divisible by 5 then use continue keyword
    # As a result, the number will not be printed.
    if temp % 5 == 0:
        continue
    else:
        print(temp)

Output:

1
2
3
4
6
7
8
9
11
12
13
14
16

Related Programs:

Python : Continue keyword in Loops Read More »

String upper() Method

Python: String upper() Method

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.

In this article we are going to discuss the use of upper() function.

String upper() Method in Python

1)Upper() function

The string upper() method returns a string that has all lowercase characters converted to uppercase characters.

Syntax:

given_string.upper()

Parameters:

The upper() method does not accept any parameters.

Return:

The upper() method returns the uppercased version of the given string. All lowercase characters are converted to uppercase.

If no lowercase characters are found, the original string is returned.

2)Converting a string to uppercase

We can convert it using built in function upper().

Below is the implementation:

# given string
string = "btech geeks"
# converting string to upper
string = string.upper()
# print the string
print(string)

Output:

BTECH GEEKS

Explanation:

It returned a copy of the given string, and all lowercase characters were converted to uppercase characters in the returned copy. The uppercase copy of the string was then assigned to the original string.

3)Converting the string which has numbers and letters to uppercase

As the above method we can convert it to uppercase using upper() function.

Below is the implementation:

# given string
string = "btech 2021 geeks"
# converting string to upper
string = string.upper()
# print the string
print(string)

Output:

BTECH 2021 GEEKS

4)Convert two strings to uppercase and compare them

We can convert the given two strings to upper() function and we can compare them using “=” operator.

Below is the implementation:

# given string
string1 = "BTechGeeks"
string2 = "btechgeeks"
# converting both strings to uppercase using upper() function
string1 = string1.lower()
string2 = string2.lower()
# compare the two strings
if(string1 == string2):
    print("Both strings are equal")
else:
    print("Both strings are not equal")

Output:

Both strings are equal

5)Convert character to uppercase

We can convert it using built in function upper().

Below is the implementation:

# given character
character = 'b'
# convert to uppercase using upper() function
character = character.upper()
# print the character
print(character)

Output:

B

Related Programs:

Python: String upper() Method Read More »

How to Remove Duplicates from a List

Python : How to Remove Duplicates from a List

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.

Example:

Input:

givenlist = ['hello', 'this', 'is', 'hello', 'BTechGeeks', 'is', 'this']

Output:

Given list with duplicates :  ['hello', 'this', 'is', 'hello', 'BTechGeeks', 'is', 'this']
Given list without duplicates :  ['hello', 'this', 'is', 'BTechGeeks']

Delete Duplicates elements from the list

We can delete duplicate elements by many methods some of them are:

Method #1:Using set

  • A set is an unordered data structure with only unique elements.
  • So, using the set() function, convert the given list to a set and then back to a list.
  • Print the list

Below is the implementation:

# given list (which contains duplicates)
givenlist = ['hello', 'this', 'is', 'hello', 'BTechGeeks', 'is', 'this']
print('Given list with duplicates : ', givenlist)
# converting givenlist to set and then back to list to remove duplicates
givenlist = list(set(givenlist))
# print given list
print('Given list without duplicates : ', givenlist)

Output:

Given list with duplicates :  ['hello', 'this', 'is', 'hello', 'BTechGeeks', 'is', 'this']
Given list without duplicates :  ['this', 'is', 'hello', 'BTechGeeks']

Note:

While this method avoids duplicates, it does not hold the elements in the same order as the original.

Method #2:Using in operator and lists (same order)

For unique elements, we’ll need to make a new list. Then iterate through the original list, adding each element to the newList only if it isn’t already there.

Below is the implementation: 

# given list (which contains duplicates)
givenlist = ['hello', 'this', 'is', 'hello', 'BTechGeeks', 'is', 'this']
print('Given list with duplicates : ', givenlist)
# taking empty list
newlist = []
# Travers the given list
for element in givenlist:
    # if the element is not present in new list then append it
    if element not in newlist:
        newlist.append(element)
# print new list
print('Given list without duplicates : ', newlist)

Output:

Given list with duplicates :  ['hello', 'this', 'is', 'hello', 'BTechGeeks', 'is', 'this']
Given list without duplicates :  ['hello', 'this', 'is', 'BTechGeeks']

Method #3:Using Counter() function (same order)

  • Counter() function is mainly used to calculate the frequencies of all elements .
  • In this case we calculate the frequencies using Counter function which returns dictionary having unique keys.
  • Convert this keys to list and print it.

Below is the implementation:

from collections import Counter
# given list (which contains duplicates)
givenlist = ['hello', 'this', 'is', 'hello', 'BTechGeeks', 'is', 'this']
print('Given list with duplicates : ', givenlist)
# counting the frequencies using Counter function
freq = Counter(givenlist)
# converting keys to list
uniquelist = list(freq.keys())
# print unqiue list
print('Given list without duplicates : ', uniquelist)

Output:

Given list with duplicates :  ['hello', 'this', 'is', 'hello', 'BTechGeeks', 'is', 'this']
Given list without duplicates :  ['hello', 'this', 'is', 'BTechGeeks']

 
Related Programs:

Python : How to Remove Duplicates from a List Read More »

While Loop with Examples

Python: While Loop with Examples

While Loops are used in Python to execute a set of statements over and over until a condition is met.. When the condition is met, the line immediately following the loop in the programme is executed. Indefinite iteration is demonstrated by the while loop. The term “indefinite iteration” refers to the fact that the number of times the loop is executed is not specified explicitly in advance.

While Loop in Python

1)Syntax:

while expression:
    statement(s)

2)Working of while loop

After a programming construct, all statements indented by the same number of character spaces are considered to be part of a single block of code.. Python’s method of grouping statements is indentation. When a while loop is run, expression is evaluated in a Boolean context and, if true, the loop body is executed. The expression is then checked again, and if it is still true, the body is executed again, and so on until the expression becomes false.

Using while loop to print first n natural numbers. let us take n=15

Below is the implementation: 

# using while loop to print natural numbers upto n
n = 15
# let us take a temp variable to 1 as natural numbers starts from 1
temp = 1
# using while loop
while(temp <= n):
    # printing temp variable
    print(temp)
    # increment the temp by 1
    temp = temp+1

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

4)Multiple conditions in while loop

In a while statement, we can have multiple conditions, and we can use ‘and’ and ‘or’ with these conditions.

Below is the implementation: 

# using while loop to print even natural numbers upto n
n = 15
# let us take a temp variable to 2 as natural numbers starts from 2
temp = 2
# using while loop
while(temp <= n and temp % 2 == 0):
    # printing temp variable
    print(temp)
    # increment the temp by 2
    temp = temp+2

Output:

2
4
6
8
10
12
14

5)While loop with else

In Python, we can have while…else blocks similar to if…else blocks, i.e., an else block after a while block.

The while loop will execute statements from the white suite multiple times until the condition is evaluated as False. When the condition in the while statement evaluates to False, control moves to the else block, where all of the statements in the else suite are executed.

Ex: Printing first n natural numbers and printing 0 at last.

Below is the implementation: 

# using while loop to print natural numbers upto n
n = 10
# let us take a temp variable to 1 as natural numbers starts from 1
temp = 1
# using while loop
while(temp <= n):
    # printing temp variable
    print(temp)
    # increment the temp by 1
    temp = temp+1
else:
    print(0)

Output:

1
2
3
4
5
6
7
8
9
10
0

Related Programs:

Python: While Loop with Examples Read More »