Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Wednesday, July 30, 2025

Python Lambda Functions With Examples

Python lambda function is a function without any name (an anonymous function) which is created using lambda keyword. Syntax of lambda function in Python is as given below.

lambda argument(s):expression

Any lambda function starts with the keyword lambda.

  • argument(s)- Parameters passed to the lambda function. Number of parameters can be 0…n.
  • expression- Logic of the lambda function.

Lambda function examples

Here is a simple example of lambda function that squares the passed number.

lambda num : num**2

Here num is the argument which is on the left side of the colon (:) and right side of it is the logic that will be executed when this lambda function is called.

The above lambda function is equivalent to the following regular function.

def square(num):
    return num ** 2

In order to execute this lambda function you can assign it to a variable. That variable essentially holds the lambda function so it can be called like a regular function using this variable.

square = lambda num : num**2
print(square(9)) #81

Another way is to immediately invoke it-

(lambda num : num**2)(9)

Some other examples of lambda functions.

1. With out any argument

msg = lambda :print("Hello")

msg() # Hello

2. Lambda function with one argument.

msg = lambda m : print(m)

msg("Hello there") # Hello there

3. Lambda function with two arguments. Gets the max of two numbers.

max = lambda x, y : x if x > y else y

print(max(17, 14)) #17

When to use lambda functions

  1. For simple operations- When logic is simple enough to be expressed in a single line and a function is needed for one time use, lambda function is a more concise and readable alternative to regular function.
  2. Used as argument for higher order functions- Higher order functions like map, filter, sorted which need another function as argument can use lambda function as that argument. That allows for the inline implementation of the function logic needed as argument in these higher order functions.

That's all for this topic Python Lambda Functions With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python
  2. Python Generator, Generator Expression, Yield Statement
  3. Python Functions: Returning Multiple Values
  4. Global Keyword in Python With Examples
  5. Namespace And Variable Scope in Python

You may also like-

  1. Python String split() Method
  2. Convert String to int in Python
  3. Magic Methods in Python With Examples
  4. List Comprehension in Python With Examples
  5. Lambda Expressions in Java 8
  6. Java Map putIfAbsent() With Examples
  7. Spring Setter Based Dependency Injection
  8. Data Loader in React Router

Friday, November 15, 2024

How to Iterate Dictionary in Python

In this tutorial we'll see how you can iterate or loop over a dictionary in Python. Some of the options are:

  1. Iterate dictionary directly
  2. Iterate a dictionary using keys method
  3. Iterate a dictionary using values method
  4. Iterate a dictionary using items method

Apart from that we'll also see how to add or remove element from a dictionary while iterating it. See example here.

1. Iterate dictionary directly

If you want to retrieve keys from a dictionary you can use a for loop directly with a dictionary.

def dictIterator(d):
    for k in d:
        print(k)
    
countries = {'US': 'United States', 'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}
#call function
dictIterator(countries)

Output

US
GB
DE
IN

Since you already retrieve keys by this way of iteration, you can also get values by passing keys to dictionary. Here is the changed code

def dictIterator(d):
    for k in d:
        print('key=', k, 'value=', d[k])
    
countries = {'US': 'United States', 'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}
dictIterator(countries)

Output

key= US value= United States
key= GB value= United Kingdom
key= DE value= Germany
key= IN value= India

2. Iterate a dictionary using keys method

Dictionary in Python has a keys() method which returns dictionary's keys as a view object. You can iterate over this view object using for loop.

def dictIterator(d):
    print(type(d.keys()))
    for k in d.keys():
        print('key=', k, 'value=', d[k])
    
countries = {'US': 'United States', 'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}
dictIterator(countries)

Output

<class 'dict_keys'>
key= US value= United States
key= GB value= United Kingdom
key= DE value= Germany
key= IN value= India

As you can see keys() method returns an object of type dict_keys.

3. Iterate a dictionary using values method

Above two ways of iterating a dictionary gives you keys of the dictionary. If you want values then there is also a values() method in dictionary which returns dictionary's values as a view object. You can iterate over this view object using for loop.

def dictIterator(d):
    print(type(d.values()))
    for v in d.values():
        print(v)
    
countries = {'US': 'United States', 'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}
dictIterator(countries)

Output

<class 'dict_values'&glt;
United States
United Kingdom
Germany
India

As you can see values() method returns an object of type dict_values.

4. Iterate a dictionary using items method

There is also a items() method in dictionary which returns a view object that contains both key and value.

def dictIterator(d):
    print(type(d.items()))
    for item in d.items():
        print(item)
    
countries = {'US': 'United States', 'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}
dictIterator(countries)

Output

<class 'dict_items'>
('US', 'United States')
('GB', 'United Kingdom')
('DE', 'Germany')
('IN', 'India')

As you can see items() method returns an object of type dict_items. Note that each item is of type tuple so you can unpack that tuple to get key and value.

def dictIterator(d):
    for k, v in d.items():
        print('Key =', k, 'Value =', v)
    
countries = {'US': 'United States', 'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}
dictIterator(countries)

Output

Key = US Value = United States
Key = GB Value = United Kingdom
Key = DE Value = Germany
Key = IN Value = India

5. Changing dictionary while looping

If you try to make a structural change in a dictionary while iterating it then RuntimeError is raised. Structural change here means adding or deleting items which changes the size of the dictionary while it is iterated. Updating any value doesn't come under structural change.

For example, trying to add new item while iterating.

def dictIterator(d):
    for k in d:
        print(k)
        d['JP'] = 'Japan'
    
countries = {'US': 'United States', 'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}
dictIterator(countries)

Output

RuntimeError: dictionary changed size during iteration

Same way trying to remove an item while iterating the dictionary results in RuntimeError.

def dictIterator(d):
    for k in d:
        print(k)
        if k == 'US':
            del d[k]
    
countries = {'US': 'United States', 'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}
dictIterator(countries)

Output

RuntimeError: dictionary changed size during iteration

In such a scenario where you are going to make a structural change to the dictionary while iterating it, you should make a shallow copy of the dictionary, using copy() method. Then you can iterate over that shallow copy and make changes to the original dictionary.

def dictIterator(d):
    #iterate copy of the dictionary
    for k in d.copy():
        if k == 'US':
            del d[k]
    print(d)
    
countries = {'US': 'United States', 'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}
dictIterator(countries)

Output

{'GB': 'United Kingdom', 'DE': 'Germany', 'IN': 'India'}

That's all for this topic How to Iterate Dictionary in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. List in Python With Examples
  2. Tuple in Python With Examples
  3. Named Tuple in Python

You may also like-

  1. Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python
  2. Global Keyword in Python With Examples
  3. Bubble Sort Program in Python
  4. String Length in Python - len() Function
  5. Java Stream - Collectors.groupingBy() With Examples
  6. Deque Implementation in Java Using Doubly Linked List
  7. JavaScript let and const With Examples
  8. Spring Integration With Quartz Scheduler

Dictionary in Python With Examples

Dictionary in Python is a built-in data type that is used to store elements in the form of key:value pairs. Value is said to be mapped with the key and you can extract the value by passing the mapped key. Dictionaries are indexed by keys and dictionaries in Python are mutable just like list in Python.

Creating a dictionary

1. You can create dictionary by storing elements with in curly braces {}. Elements here are comma separated key:value pairs. Each key:value pair has colon ( : ) in between.

Syntax

d = {
    key1: value1,
    key2: value2,
      .
      .
      .
    keyn: valuen
}

Here are some examples of creating dictionary.

#empty dictionary
d = {}
print(d) #{}

#dictionary with int as key and string as value
d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'}
print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'}

# nested dictionary- Each value is another dictionary
d = {'1001':{'id':1001, 'name':'Ram', 'age': 43}, '1002':{'id':1002, 'name':'Chaya', 'age': 34}}
print(d) #{'1001': {'id': 1001, 'name': 'Ram', 'age': 43}, '1002': {'id': 1002, 'name': 'Chaya', 'age': 34}}

2. You can also create a dictionary using the dict() constructor by passing a sequence of key-value pairs.

Syntax

d = dict([
    (key1, value1),
    (key2, value2),
      .
      .
      .
    (keyn: valuen)
])

Here are some examples of creating dictionary using dict() constructor.

d = dict([(1, 'Ashish'), (2, 'Bhavya'), (3, 'Chandan'), (4, 'Dinesh')])
print(d) # {1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'}

When the keys are simple strings, you can also specify pairs using keyword arguments.

d = dict(NDL='New Delhi', KOL='Kolakata', MUM='Mumbai', HYD='Hyderabad')
print(d) # {'NDL': 'New Delhi', 'KOL': 'Kolkata', 'MUM': 'Mumbai', 'HYD': 'Hyderabad'}

Python 3.7 onward, dictionaries preserve insertion order, meaning that keys will be produced in the same order they were added sequentially over the dictionary.

Retrieving value in dictionary

Once dictionary is created you can access any value by passing the mapped key.

d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'}
val = d[1]
print(val) # Ashish

As you can see by passing key 1 you get the mapped value 'Ashish'

d = dict(NDL='New Delhi', KOL='Kolkata', MUM='Mumbai', HYD='Hyderabad')
print(d['KOL']) #Kolkata

If you pass any key which is not present in the dictionary, Python raises KeyError exception.

d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'}
val = d[10]
print(val)

Output

Traceback (most recent call last):

  File d:\netjs\netjs_2017\python\pythonnewws\mydictionary.py:9
    val = d[10]

KeyError: 10

Retrieving value in nested dictionary

You can retrieve value from the nested dictionary by passing respective keys in square brackets.

For example-

d = {'1001':{'id':1001, 'name':'Ram', 'age': 43}, '1002':{'id':1002, 'name':'Chaya', 'age': 34}}

Here we have nested dictionary mapped with each key. If we want to retrieve name as 'Ram' then we first have to pass key as '1001' to get the mapped value. Since value is again a dictionary so we need to pass another key as 'name' to get the mapped value.

d['1001']['name']

Retrieving value using get method in dictionary

In the previous example we have seen that passing a key that is not present in the dictionary results in KeyError. If you want to avoid that you can use get method which has the following syntax.

get(key, default=None)

Method returns the value for key if key is in the dictionary, else default. If default value is not passed, it defaults to None, so that this method never raises a KeyError.

d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'}
val = d.get(10, 'Not Found')
print(val) #Not Found

Adding new key:value pair

Adding new key:value pair to the dictionary is done by assigning value to a respective key.

d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'}
# new key:value
d[5] = 'Esha'
print(d) # {1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh', 5: 'Esha'}

Updating value for an existing key

If you want to update value for an existing key that can be done by assigning value to that key.

d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'}
#changed value for key=3
d[3] = 'Chirag'
print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chirag', 4: 'Dinesh'}

Removing element from Dictionary

A key:value pair can be removed from a dictionary using del statement.

d = dict([(1, 'Ashish'), (2, 'Bhavya'), (3, 'Chandan'), (4, 'Dinesh')])
print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'}
del(d[2])
print(d) #{1: 'Ashish', 3: 'Chandan', 4: 'Dinesh'}

There is also a pop(key[,default]) method in dictionary which removes the key if it is in the dictionary and returns its value, else returns default. If default is not given and key is not in the dictionary, a KeyError is raised.

d = dict([(1, 'Ashish'), (2, 'Bhavya'), (3, 'Chandan'), (4, 'Dinesh')])
print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'}
print(d.pop(2)) #Bhavya
print(d) #{1: 'Ashish', 3: 'Chandan', 4: 'Dinesh'}

Getting the count of items in a dictionary

You can get the count of items in a dictionary using len() function.

len(d)- Returns the count of items in the dictionary d.

d = dict([(1, 'Ashish'), (2, 'Bhavya'), (3, 'Chandan'), (4, 'Dinesh')])
print(len(d)) #4

Rules for keys in the dictionary

Dictionary in Python has certain rules for keys.

1. Key should be immutable. You can use any datatype as key which is immutable like strings and numbers. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key.

This restriction is there because immutable datatypes are hashable. Dictionary is a HashTable based data structure which uses key to calculate a hash value to determine where to store the mapped value. For retrieval hash value of the passed key is calculated to determine the location of the value.

In the example code one of the keys is a list.

code = ['NDL']
city = {code: 'New Delhi', 'KOL': 'Kolkata', 'MUM': 'Mumbai', 'HYD': 'Hyderabad'}
print(city)

Output

File d:\netjs\netjs_2017\python\pythonnewws\mydictionary.py:9
    city = {code: 'New Delhi', 'KOL': 'Kolkata', 'MUM': 'Mumbai', 'HYD': 'Hyderabad'}

TypeError: unhashable type: 'list'

2. Keys in a dictionary should be unique, if you pass the same key again that doesn't result in an error but overwrites the previous value.

In the example code key 3 is duplicate.

d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh', 3:'Chirag'}
print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chirag', 4: 'Dinesh'}

Methods in Python dictionary

Some of the operations supported by dictionaries in Python.

1. clear()- Used to remove all items from the dictionary.

d = dict(NDL='New Delhi', KOL='Kolkata', MUM='Mumbai', HYD='Hyderabad')
print(d) #{'NDL': 'New Delhi', 'KOL': 'Kolkata', 'MUM': 'Mumbai', 'HYD': 'Hyderabad'}
d.clear()
print(d) #{}

2. items()- Returns a view object that contains each key:value pair as a tuple in a list.

d = dict(NDL='New Delhi', KOL='Kolkata', MUM='Mumbai', HYD='Hyderabad')
print(d.items()) #dict_items([('NDL', 'New Delhi'), ('KOL', 'Kolkata'), ('MUM', 'Mumbai'), ('HYD', 'Hyderabad')])

3. keys()- Returns a view object of the dictionary's keys.

d = dict(NDL='New Delhi', KOL='Kolkata', MUM='Mumbai', HYD='Hyderabad')
print(d.keys()) # dict_keys(['NDL', 'KOL', 'MUM', 'HYD'])

4. pop()- Removes an element from the dictionary for the passed key and returns the value.

d = dict([(1, 'Ashish'), (2, 'Bhavya'), (3, 'Chandan'), (4, 'Dinesh')])
print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'}
print(d.pop(2)) #Bhavya
print(d) #{1: 'Ashish', 3: 'Chandan', 4: 'Dinesh'}

5. popitem()- Remove and return a (key, value) pair from the dictionary. Pairs are returned in LIFO order Python 3.7 onward, before that it used to remove a random element.

d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'}
print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'}
print(d.popitem()) #(4, 'Dinesh')
print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan'}

6. setdefault(key, default=None)- Method returns the values of the key if it is present in the dictionary. If key is not present in the dictionary then inserts key with a value of default and returns default.

In the following code there is no change in the dictionary.

d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'}
print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'}
print(d.setdefault(3, 'Chirag')) #Chandan
print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'}

With the following code a new item is added to the dictionary.

d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'}
print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'}
print(d.setdefault(5, 'Esha')) #Esha
print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh', 5: 'Esha'}

7. update(other)- This method is used to merge dictionary with other dictionary. While merging if the same key is present in other then it overwrites the existing key's value.

names = {4:'Divya', 5:'Esha'}
d = {1:'Ashish', 2:'Bhavya', 3:'Chandan', 4:'Dinesh'}
print(d) #{1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Dinesh'}
print(names) #{4: 'Divya', 5: 'Esha'}
d.update(names)
print(d) # {1: 'Ashish', 2: 'Bhavya', 3: 'Chandan', 4: 'Divya', 5: 'Esha'}

8. values()- Returns a view object of the dictionary's values.

city = {'NDL': 'New Delhi', 'KOL': 'Kolkata', 'MUM': 'Mumbai', 'HYD': 'Hyderabad'}
print(city.values())

Output

dict_values(['New Delhi', 'Kolkata', 'Mumbai', 'Hyderabad'])

That's all for this topic Dictionary in Python With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. How to Iterate Dictionary in Python
  2. List Comprehension in Python With Examples
  3. Concatenating Lists in Python
  4. Tuple in Python With Examples
  5. Named Tuple in Python

You may also like-

  1. Magic Methods in Python With Examples
  2. Python String replace() Method
  3. Passing Object of The Class as Parameter in Python
  4. Inheritance in Python
  5. Bounded Type Parameter in Java Generics
  6. static Block in Java
  7. Spring Web MVC Tutorial
  8. Angular Reactive Form Validation Example

Wednesday, November 13, 2024

List Comprehension in Python With Examples

List comprehension in Python is a simple way to create a List from an iterable, it consists of an expression, a loop, an iterable that is iterated using the loop and an optional condition enclosed in a bracket.

Syntax of list comprehension in Python is as given below-

other_list = [expression for iterable_items if condition]

Here for loop is used to generate items for the list by iterating the items of the given iterable. Optional condition is used to filter items if required.

The syntax of list comprehension is equivalent to the following traditional way of list creation-

other_list = []
for item in iterable:
 if condition:
  other_list.append(expression_using_item)

List comprehension Python examples

1. A simple example using the for loop with a range function to create a list of numbers with in a given range.

num_list = [num for num in range(1, 5)]
print(num_list) # [1, 2, 3, 4]

2. Creating a list by iterating alphabets of a word in a String.

name = 'Michael'
alphabet_list = [a for a in name]
print(alphabet_list) #['M', 'i', 'c', 'h', 'a', 'e', 'l']

3. Creating list from another list where each element of the list is multiplied by 2.

num_list = [2, 4, 6, 8]

another_list = [num * 2 for num in num_list]
print(another_list) # [4, 8, 12, 16]

4. List comprehension example of list creation using another list where if condition is also used to filter out items.

name_list = ['Michael', 'Jay', 'Jason', 'Ryan']
another_list = [a for a in name_list if len(a) >= 5]
print(another_list) #['Michael', 'Jason']

5. Sum of the items of two lists to create a new list using list comprehension.

num_list1 = [1, 2, 3, 4]
num_list2 = [5, 6, 7, 8]

another_list = [num_list1[i]+num_list2[i] for i in range(len(num_list1))]
print(another_list) #[6, 8, 10, 12]

6. Find common elements between two lists using list comprehension.

num_list1 = [1, 2, 3, 4]
num_list2 = [4, 8, 2, 5]

common_list = [a for a in num_list1 for b in num_list2 if a == b]
print(common_list) # [2, 4]

Which is equivalent to the following code.

common_list = []
for a in num_list1:
    for b in num_list2:
        if a == b:
            common_list.append(a)
print(common_list)

Finding common elements can also be done in the following way-

common_list = [a for a in num_list1 if a in num_list2]
print(common_list)

That's all for this topic List Comprehension in Python With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. List in Python With Examples
  2. Tuple in Python With Examples
  3. Python Conditional Statement - if, elif, else Statements
  4. Python Generator, Generator Expression, Yield Statement
  5. Magic Methods in Python With Examples

You may also like-

  1. Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python
  2. Python Program to Check Armstrong Number
  3. Interface in Python
  4. Accessing Characters in Python String
  5. How LinkedList Class Works Internally in Java
  6. Java StampedLock With Examples
  7. Constructor Chaining in Java
  8. How to Create PDF From XML Using Apache FOP

Thursday, May 16, 2024

Tuple in Python With Examples

Tuple in Python is one of the sequence data type that can store a group of elements. Tuple is similar to Python list with one notable difference that the Tuple is immutable where as list is mutable.

Once a tuple is created you can’t modify its elements. So performing operations like insert(),remove(), pop(), clear() are not possible on tuples.

Some of the important points about Python Tuple are-

  1. A tuple can store elements of different types.
  2. Tuple maintains the insertion order. Elements are inserted sequentially and you can iterate them in the same order.
  3. Tuple is immutable. So, it is not possible to change content of a tuple.
  4. Tuples can be indexed (both positive and negative) and sliced.

In this article we’ll see some of the features of the Python tuples with examples, methods in Tuple and functions that can be used with tuple.


Creating a tuple

1. In Python tuple is created by grouping elements with in parenthesis (), where the elements are separated by comma. It is the preferred way and also necessary in some scenarios.

# empty tuple
t = ()
print(t)

# tuple with items having different types
t = (12, 54, 'hello!')
print(t)

# tuple containing lists
t = ([1, 2, 3], [4, 5, 6])
print(t)

Output

()
(12, 54, 'hello!')
([1, 2, 3], [4, 5, 6])

Here note that though Tuple itself is immutable but it can contain mutable objects like list.

2. When a tuple with one item is constructed value should be followed by a comma (it is not sufficient to enclose a single value in parentheses).

t = (1)
print(type(t))

t = (1,)
print(type(t))

Output

<class 'int'>
<class 'tuple'>

As you can see, in first assignment type of t is integer not tuple. In the second assignment when value is followed by comma, the type of t is tuple.

3. You can also create a tuple using tuple() type constructor. An iterable can be passed as an argument to create a tuple, if no argument is passed then an empty tuple is created.

t = tuple()
print(t)
print(type(t))

Output

()
<class 'tuple'>

When argument is passed-

#Tuple as argument
t = tuple((1,2,3)) 
print(t)
print(type(t))

#List as argument
t = tuple([1, "Test", 4.56])
print(t)
print(type(t))

Output

(1, 2, 3)
<class 'tuple'>
(1, 'Test', 4.56)
<class 'tuple'>

Tuple packing and unpacking

Tuple can also be created without using parenthesis, it is known as tuple packing.

t = 3, 4, 'Hello'
print(t)
print(type(t))

Output

(3, 4, 'Hello')
<class 'tuple'>

You can also do tuple unpacking by assigning tuple items to variables, unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence.

#packing
t = 3, 4, 'Hello'
print(t)
print(type(t))

#unpacking
x, y, z = t
print('x',x)
print('y',y)
print('z',z)

Output

(3, 4, 'Hello')
<class 'tuple'>
x 3
y 4
z Hello

Accessing tuple elements using index

Tuple in python uses index starting from 0 to (tuple_length-1), it also uses negative indexing which starts at -1 from the end (right most element) and goes till tuple_length.

Here is an example showing tuple indexing for the stored elements.

To access an element of the tuple you can pass the corresponding index in the square brackets. For example to access the 5th element in a tuple you will pass tuple[4], as index starts from 0.

t = (2, 3, 6, 7, 9)
# 1st element
print(t[0])

#last element
print(t[4])

#last element
print(t[-1])

#first element
print(t[-5])

Output

2
9
9
2

Trying to pass index beyond the index range of the tuple results in ‘index error’. For example here is a tuple having 5 elements so index range for the tuple is 0..4, trying to access index 5 results in an error.

t = (2, 3, 6, 7, 9)
print(t[6])

Output

IndexError: tuple index out of range

Slicing a tuple

Just like string slicing you can do tuple slicing too which returns a new tuple.

Format of tuple slicing is as follows-

Tupleobject[start_position: end_position: increment_step]
  • start_position is the index from which the slicing starts, start_position is included.
  • end_position is the index at which the tuple slicing ends, end_position is excluded.
  • increment_step indicates the step size. For example if step is given as 2 then every alternate element from start_position is accessed.

All of these parameters are optional, if start_position is not specified then the slicing starts from index 0. If end_position is not specified then the slicing ends at list_length – 1 (last index). If increment_step is not specified then increment step is 1 by default.

t = [2, 4, 6, 8, 10]
print(t[1:len(t):2]) #[4, 8]


t = [2, 4, 6, 8, 10]
print(t[::])#[2, 4, 6, 8, 10]
print(t[-3:])#[6, 8, 10]

Methods in tuple

Tuples provide the following two methods-

  • count(x)- Returns the number of items x
  • index(x)- Returns the index of the first item that is equal to x

Functions that can be used with tuple

  • len- The len() function returns the number of items of a sequence
  • min- The min() function returns the minimum element in a sequence
  • max- The max() function returns the maximum element in a sequence
  • sorted- Return a new sorted list from the items in iterable.

Operators used with tuples

Tuples can be used with the following operators which result in a creation of new tuple.

  • + (concatenation)
  • * (replication)
  • [] (slice)

Iterating a tuple

You can iterate all elements of a tuple using for or while loop.

1. Using for loop

t = [3, 1, 9, 2, 5]
for i in t:
  print(i)

Output

3
1
9
2
5

2. Using while loop

t = [3, 1, 9, 2, 5]
i = 0;
while i < len(t):
  print(t[i])
  i += 1

Output

3
1
9
2
5

del keyword with tuple

Since tuple is immutable so elements can’t be modified or removed from a tuple but tuple itself can be deleted entirely using del keyword along with tuple instance.

t = [3, 1, 9, 2, 5]

print(t)
del t
print(t)

Output

[3, 1, 9, 2, 5]
   print(t)
NameError: name 't' is not defined

Second print(t) statement results in an error as tuple t is already deleted.

That's all for this topic Tuple in Python With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Named Tuple in Python
  2. List Comprehension in Python With Examples
  3. String Length in Python - len() Function
  4. Python Functions : Returning Multiple Values
  5. Constructor in Python - __init__() function

You may also like-

  1. Python while Loop With Examples
  2. Multiple Inheritance in Python
  3. Installing Anaconda Distribution On Windows
  4. Python Program to Display Fibonacci Series
  5. Java Multithreading Interview Questions And Answers
  6. Dependency Injection in Spring Framework
  7. String in Java Tutorial
  8. Volatile Keyword in Java With Examples

Thursday, January 4, 2024

Bubble Sort Program in Python

In this post we’ll see how to write Bubble sort program in Python. Bubble sort is considered the simplest sorting algorithm out of the three simpler sorting algorithms bubble sort, insertion sort and selection sort. Bubble sort is considered the slowest too because of a proportionally large number of swaps along with the comparisons.

How does Bubble sort work

In Bubble sort adjacent elements are compared and swapped if element at left is greater than element at right. For example if n[0] and n[1] are compared and n[0] > n[1] then n[0] and n[1] are swapped. Then you move by one index and compare the adjacent elements i.e. n[1] and n[2].

By the end of first pass you should have the maximum element in the list at the rightmost position. Since the maximum element bubbles up to the top thus the name Bubble sort.

To sum up the steps for bubble sort-

  1. Compare the adjacent elements.
  2. If element at the left is greater than the element at the right then swap the elements.
  3. Move one position right. Start from point 1.

In the next pass again you start from the two leftmost elements and compare the elements and swap if required. Since the rightmost element is already in its sorted position so this pass runs till (N-1) elements.

For example if you have an array [5, 3, 8, 2] then in the first pass-

Iteration 1- Initially 5 is compared with 3, since 5 (element at left) is greater than 3 (element at right), elements are swapped making the array [3, 5, 8, 2].

Iteration 2- Move to next position and compare element at index 1 and index 2 (5 and 8), since 5 is not greater than 8 so swapping is not done and array remains [3, 5, 8, 2].

Iteration 3- Again move over one position and compare 8 and 2. Since 8 is greater than 2, elements are swapped giving us the array as [3, 5, 2, 8].

As you can see by the end of first pass the maximum element is at the rightmost position. In the next pass last element is not included in the comparison as it is already at its final position so the array that is considered for comparison and swapping effectively becomes [3, 5, 2].

Bubble Sort Python program

def bubble_sort(nlist):
  list_length = len(nlist)
  # reduce length by 1 in each pass
  for i in range(list_length-1, 0, -1):
    for j in range(i):
      # compare
      if nlist[j] > nlist[j+1]:
        # swap elements
        nlist[j+1], nlist[j] = nlist[j], nlist[j+1]

nlist = [47, 85, 62, 34, 7, 10, 92, 106, 2, 54]
print('Original List-', nlist)
bubble_sort(nlist)
print('Sorted List-', nlist)

Output

Original List- [47, 85, 62, 34, 7, 10, 92, 106, 2, 54]
Sorted List- [2, 7, 10, 34, 47, 54, 62, 85, 92, 106]

Time and Space complexity of Bubble sort

In Bubble sort (N-1) comparisons are required in the first pass, (N-2) comparisons in the second pass, (N-3) comparisons in the third pass and so on.

So the total number of comparisons is- N(N-1)/2

Thus the time complexity of Bubble sort is O(n2).

Bubble sort is an in-place sorting algorithm and doesn’t require any auxiliary space so the space complexity of Bubble sort is O(1).

That's all for this topic Bubble Sort Program in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Check Armstrong Number
  2. Python Program to Check if Strings Anagram or Not
  3. Python break Statement With Examples
  4. List in Python With Examples
  5. String Slicing in Python

You may also like-

  1. User-defined Exceptions in Python
  2. Functions in Python
  3. Local, Nonlocal And Global Variables in Python
  4. Python count() method - Counting Substrings
  5. Difference Between HashMap And Hashtable in Java
  6. Binary Search Program in Java
  7. String Pool in Java
  8. Spring Boot Spring Initializr

Sunday, November 5, 2023

Installing Anaconda Distribution On Windows

In this post we'll see how you can install Anaconda distribution on Windows.

Anaconda Distribution is a free, easy-to-install package manager, environment manager, and Python distribution with a collection of 1,500+ open source packages. This gives you an advantage that many different packages like numpy, pandas, scipy come pre-installed. If you need any other package you can easily install it using the Anaconda's package manager Conda.

Jupyter Notebook which is an incredibly powerful tool for interactively developing and presenting data science projects also comes pre-installed with Anaconda distribution.

You also get Spyder IDE pre-installed with Anaconda.

Anaconda is platform-agnostic, so you can use it whether you are on Windows, macOS, or Linux.

URL for downloading Anaconda

You can download Anaconda disribution from this location- https://www.anaconda.com/distribution/

There you will see the option to install for Windows, macOS, Linux. Select the appropriate platform using the tabs. With in the selected platform chose the version of Python you want to install and click on download.

Installing Anaconda Distribution

Installation Process

Once the download is done double click the installer to launch. Click Next.

Read the licensing terms and click “I Agree”.

Select an install for “Just Me” unless you’re installing for all users (which requires Windows Administrator privileges) and click Next.

Select a destination folder to install Anaconda and click the Next button.

Choose whether to add Anaconda to your PATH environment variable. Anaconda recommends not to add Anaconda to the PATH environment variable, since this can interfere with other software. Instead, use Anaconda software by opening Anaconda Navigator or the Anaconda Prompt from the Start Menu.

Anaconda installation options

Click the Install button. If you want to watch the packages Anaconda is installing, click Show Details. Click the Next button.

Once the installation is complete. Click next.

Click Finish at the end to finish setup.

Verifying your installation

First thing is to check the installed software. In windows click start and look for Anaconda.

Anaconda installation menu options

To confirm that Anaconda is installed properly and working with Anaconda Navigator and conda, follow the given steps.

  1. Anaconda Navigator is a graphical user interface that is automatically installed with Anaconda. Navigator will open if the installation was successful. If Navigator does not open that means there is some problem with the installation.
  2. Conda is a command line interface (CLI), you can use conda to verify the installation using Anaconda Prompt on Windows or terminal on Linux and macOS. To open Anaconda Prompt select Anaconda Prompt from the menu. After the prompt is opened-
    • Enter command conda list. If Anaconda is installed and working, this will display a list of installed packages and their versions.
    • Enter the command python. This command runs the Python shell.

That's all for this topic Installing Anaconda Distribution On Windows. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Functions in Python
  2. Python count() method - Counting Substrings
  3. Constructor in Python - __init__() function
  4. Multiple Inheritance in Python
  5. Namespace And Variable Scope in Python

You may also like-

  1. Variable Length Arguments (*args), Keyword Varargs (**kwargs) in Python
  2. Bubble Sort Program in Python
  3. Operator Overloading in Python
  4. List in Python With Examples
  5. How to Install Java in Ubuntu
  6. Installing Hadoop on a Single Node Cluster in Pseudo-Distributed Mode
  7. HashSet in Java With Examples
  8. Shallow Copy And Deep Copy in Java Object Cloning

Sunday, January 29, 2023

Concatenating Lists in Python

In this post we’ll see how to concatenate or join two lists in Python.

1. The best way to join two lists in Python is to use ‘+’ operator.

num_list1 = [1,2,3,4]
num_list2 = [5,6,7]
#concatenating lists using + operator
num_list1 = num_list1 + num_list2
print('Joined List-', num_list1)

Output

Joined List- [1, 2, 3, 4, 5, 6, 7]

2. If you are asked to write a program to join two lists in Python without using any inbuilt function or operator then you can use for loop to iterate one of the list and add elements to another list.

num_list1 = [1,2,3,4]
num_list2 = [5,6,7]
# iterate elements of list
for i in num_list2:
    num_list1.append(i)
print('Joined List-', num_list1)

Output

Joined List- [1, 2, 3, 4, 5, 6, 7]

3. You can also join two lists using list comprehension in Python. Trick here is to create a list of lists and then flatten it.

num_list1 = [1, 2, 3, 4]
num_list2 = [5, 6, 7, 8]
joined_list = [j for s in (num_list1, num_list2) for j in s]
print('Joined List-', joined_list)

Output

Joined List- [1, 2, 3, 4, 5, 6, 7, 8]

4. For joining two lists you can also use list.extend() method where you can pass another list as argument.

num_list1 = [1, 2, 3, 4]
num_list2 = [5, 6, 7, 8]
num_list1.extend(num_list2)
print('Joined List-', num_list1)

Output

Joined List- [1, 2, 3, 4, 5, 6, 7, 8]

5. Using itertools.chain(*iterables) method that make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

This method returns itertools.chain object which is a generator iterator. By passing it to list() type constructor you can get joined list.

import itertools
num_list1 = ['a', 'b', 'c', 'd']
num_list2 = ['e', 'f', 'g', 'h']
joined_list = list(itertools.chain(num_list1, num_list2))

print('Joined List-', joined_list)

Output

Joined List- ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

That's all for this topic Concatenating Lists in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. List in Python With Examples
  2. Named Tuple in Python
  3. Python for Loop With Examples
  4. String Length in Python - len() Function
  5. Keyword Arguments in Python

You may also like-

  1. Magic Methods in Python With Examples
  2. Python Program to Count Occurrences of Each Character in a String
  3. Interface in Python
  4. String Slicing in Python
  5. ArrayList in Java With Examples
  6. final Keyword in Java With Examples
  7. Just In Time Compiler (JIT) in Java
  8. Spring Job Scheduling Using TaskScheduler And @Scheduled Annotation

Thursday, January 19, 2023

List in Python With Examples

List in Python is one of the sequence data type that can store a group of elements. Some of the important points about Python list are-

  1. A list can store elements of different types.
  2. List maintains the insertion order. Elements are inserted sequentially and you can iterate them in the same order.
  3. One of the major difference between list and other data types like string and tuple is that list is mutable. So, it is possible to change content of a list.
  4. Lists can be indexed (both positive and negative) and sliced.

In this article we’ll see some of the features of the Python list, methods of the list and functions that can be used with List with examples.


Creating a list in Python

In Python list is created by grouping elements with in square brackets [], where the elements are separated by comma.

1. A list of integers.

numbers = [1, 3, 5, 7]
print(numbers) # [1, 3, 5, 7]

2. Creating empty list in Python.

alist = []
print(alist) # []

3. List with element of different types.

alist = [12, 'Sheldon', 'M', 9.99, 9.98]
print(alist)
print(type(alist[0]))
print(type(alist[1]))
print(type(alist[3]))

Output

[12, 'Sheldon', 'M', 9.99, 9.98]
<class 'int'>
<class 'str'>
<class 'float'>

As you can see type of the element at the 0th index is int, type of the element at the 1st index is str where as type of the element at the 3rd index is float.

4. Creating list using type constructor- list()

By passing an iterable in the type constructor list() you can create a list. If no argument is given, the constructor creates a new empty list, [].

alist = list((1,2,3,4))
print(alist) #[1, 2, 3, 4]
alist = list('abcd')
print(alist) #['a', 'b', 'c', 'd']
alist = list(range(1, 9, 2))
print(alist) #[1, 3, 5, 7]

5. Creating a nested list.

You can create a list with in another list (nested list) by grouping elements enclosed in a square bracket with in a square bracket.

alist = [1, 2, [3, 4], 5, 6]
print(alist) #[1, 2, [3, 4], 5, 6]

Refer this post List Comprehension in Python With Examples to see an elegant way to create a list using list comprehension.

Accessing Python List elements using index

List in python uses index starting from 0 to (list_length-1), it also uses negative indexing which starts at -1 from the end (right most element) and goes till list_length.

Here is an example showing list indexing for the stored elements.

Python List index

To access an element you can pass the index in the square brackets. For example to access the 5th element in a list you will pass list[4], as index starts from 0.

alist = [2, 3, 6, 7, 9]
#1st element
print(alist[0])
#last element
print(alist[4])
#last element
print(alist[-1])
#first element
print(alist[-5])

Output

2
9
9
2

Trying to pass index beyond the index range of the list results in ‘index error’. For example here is a list having 5 elements so index range for the list is 0..4, trying to access index 5 results in an error.

alist = [2, 3, 6, 7, 9]
print(alist[5])

Output

    print(alist[5])
IndexError: list index out of range

Slicing a list in Python

Just like string slicing in Python you can do list slicing too which returns a new list.

Format of List slicing is as follows-

Listname[start_position: end_position: increment_step]
  • start_position is the index from which the slicing starts, start_position is included.
  • end_position is the index at which the list slicing ends, end_position is excluded.
  • increment_step indicates the step size. For example if step is given as 2 then every alternate element from start_position is accessed.

All of these parameters are optional, if start_position is not specified then the slicing starts from index 0. If end_position is not specified then the slicing ends at list_length – 1 (last index). If increment_step is not specified then increment step is 1 by default.

alist = [2, 4, 6, 8, 10]
print(alist[1:len(alist):2]) #[4, 8]

In the example start_position is 1, end_position is 5 and increment_step is 2 thus the elements at indices 1 and 3 are sliced to create another list.

alist = [2, 4, 6, 8, 10]
print(alist[::])#[2, 4, 6, 8, 10]
print(alist[-3:])#[6, 8, 10]

Iterating all elements of a list using for or while loop

1. Using for loop

alist = [2, 4, 6, 8, 10]
for i in alist:
  print(i)

Output

2
4
6
8
10

As you can see from the output insertion order is maintained in the list.

2. Using while loop

alist = [2, 4, 6, 8, 10]
i = 0;
while i < len(alist):
  print(alist[i])
  i += 1

Output

2
4
6
8
10

Adding elements to a list

To add elements to a list you can use one of the following methods-

  • list.append(x)- Add an item to the end of the list.
  • list.insert(i, x)- Insert an item at a given position. The first argument is the index of the element before which to insert.
  • list.extend(iterable)- Extend the list by appending all the items from the iterable.
alist = [2, 4, 6, 8, 10]
# add new element at the end
alist.append(12)
print(alist)
# insert element before index 4
alist.insert(4, 9)
print(alist)
# append elements from another list
alist.extend([14, 16])
print(alist)

Output

[2, 4, 6, 8, 10, 12]
[2, 4, 6, 8, 9, 10, 12]
[2, 4, 6, 8, 9, 10, 12, 14, 16]

Updating elements of a list in Python

Since Python list is mutable so value of the elements in the list can be modified or elements can be deleted.

To update element’s value you need to access that element using indexing or slicing and assign a new value.

alist = [2, 4, 6, 8, 10]
#Updating value of the element at 3rd index
alist[3] = 9
print(alist) #[2, 4, 6, 9, 10]

Using slicing

alist = [2, 4, 6, 8, 10]
#Updating element at 0th and 1st index
alist[0:2] = 1, 2
print(alist) #[1, 2, 6, 8, 10]

Removing element from a Python list

You can remove element from a list using one of the following method.

  • list.remove(x)- Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
  • list.pop([i])- Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. If index is out of range then IndexError is raised.

Python list remove() method example

alist = ['h', 'e', 'l', 'l', 'o']
if 'e' in alist:
  alist.remove('e')
print(alist)

Output

['h', 'l', 'l', 'o']

In the example using membership operator ‘in’ first it is checked whether the element exists in the lists or not, if it does then it is removed using remove() method.

Python list pop() method example

alist = ['h', 'e', 'l', 'l', 'o']
elem = alist.pop(2)
print(elem)

Output

l

That's all for this topic List in Python With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Concatenating Lists in Python
  2. Tuple in Python With Examples
  3. Named Tuple in Python
  4. Python while Loop With Examples
  5. Python Generator, Generator Expression, Yield Statement

You may also like-

  1. Python Conditional Statement - if, elif, else Statements
  2. Operator Overloading in Python
  3. Python Program to Check if Strings Anagram or Not
  4. raise Statement in Python Exception Handling
  5. Java Collections Interview Questions And Answers
  6. Volatile Keyword in Java With Examples
  7. Difference Between throw And throws in Java
  8. Quick Sort Program in Java

Wednesday, December 21, 2022

Python Program to Display Armstrong Numbers

In this post we'll see a Python program to display Armstrong numbers with in the given range.

An Armstrong number is a number that is equal to the sum of the digits in a number raised to the power of number of digits in the number.

For example 371 is an Armstrong number. Since the number of digits here is 3, so

371 = 33 + 73 + 13 = 27 + 343 + 1 = 371

Another Example is 9474, here the number of digits is 4, so

9474 = 94 + 44 + 74 + 44 = 6561 + 256 + 2401 + 256 = 9474

Display Armstrong numbers Python program

In the program user is prompted to input lower and upper range for displaying Armstrong numbers. Then run a for loop for that range, checking in each iteration whether the number is an Armstrong number or not.

def display_armstrong(lower, upper):
  for num in range(lower, upper + 1):
    digitsum = 0
    temp = num
    # getting length of number
    no_of_digits = len(str(num))
    while temp != 0:
      digit = temp % 10
      # sum digit raise to the power of no of digits
      digitsum += (digit ** no_of_digits)
      temp = temp // 10
    # if sum and original number equal then Armstrong number
    if digitsum == num:
      print(num, end=' ')

def get_input():
  """Function to take user input for display range"""
  start = int(input('Enter start number for displaying Armstrong numbers:'))
  end = int(input('Enter end number for displaying Armstrong numbers:'))
  # call function to display Armstrong numbers
  display_armstrong(start, end)

# start program
get_input()

Output

Enter start number for displaying Armstrong numbers:10
Enter end number for displaying Armstrong numbers:10000
153 370 371 407 1634 8208 9474 

That's all for this topic Python Program to Display Armstrong Numbers. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Display Prime Numbers
  2. Convert String to float in Python
  3. Python Program to Count Number of Words in a String
  4. Check String Empty or Not in Python
  5. Comparing Two Strings in Python

You may also like-

  1. Ternary Operator in Python
  2. Polymorphism in Python
  3. Abstract Class in Python
  4. Magic Methods in Python With Examples
  5. Difference Between Comparable and Comparator in Java
  6. Java Semaphore With Examples
  7. Converting Enum to String in Java
  8. Sending Email Using Spring Framework Example

Friday, December 9, 2022

Python Program to Check Prime Number

In this post we'll see a Python program to check whether the passed number is a prime number or not. This program also shows a use case where for loop with else in Python can be used.

A number is a prime number if it can only be divided either by 1 or by the number itself. So the passed number has to be divided in a loop from 2 till number/2 to check if number is a prime number or not.

You need to start loop from 2 as every number will be divisible by 1.

You only need to run your loop till number/2, as no number is completely divisible by a number more than its half. Reducing the iteration to N/2 makes your program to display prime numbers more efficient.

Check prime number or not Python program

def check_prime(num):
  for i in range(2, num//2+1):
    # if number is completely divisible then it
    # it is not a prime number so break out of loop
    if num % i == 0:
      print(num, 'is not a prime number')
      break
  # if loop runs completely that means a prime number
  else:
    print(num, 'is a prime number')

check_prime(13)
check_prime(12)
check_prime(405)
check_prime(101)

Output

13 is a prime number
12 is not a prime number
405 is not a prime number
101 is a prime number

That's all for this topic Python Program to Check Prime Number. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Count Occurrences of Each Character in a String
  2. Python Program to Display Fibonacci Series
  3. Python Program to Display Prime Numbers
  4. Python break Statement With Examples
  5. Changing String Case in Python

You may also like-

  1. Python Exception Handling - try,except,finally
  2. Getting Substring in Python String
  3. Constructor in Python - __init__() function
  4. Name Mangling in Python
  5. Java Stream API Tutorial
  6. Difference Between Checked And Unchecked Exceptions in Java
  7. Selection Sort Program in Java
  8. Spring Bean Life Cycle

Thursday, December 8, 2022

Python Program to Check Armstrong Number

In this post we'll see a Python program to check if a given number is an Armstrong number or not.

An Armstrong number is a number that is equal to the sum of the digits in a number raised to the power of number of digits in the number.

For example 371 is an Armstrong number. Since the number of digits here is 3, so-

371 = 33 + 73 + 13 = 27 + 343 + 1 = 371

Another Example is 9474, here the number of digits is 4, so

9474 = 94 + 44 + 74 + 44 = 6561 + 256 + 2401 + 256 = 9474

Check Armstrong number or not Python program

In the program user is prompted to input a number. Number of digits in that number is calculated using len() function that takes string as input that is why number is cast to str.

In the loop add each digit of the input number raised to the power of number of digits. After the control comes out of loop if sum and the input number are equal then it is an Armstrong number otherwise not.

def check_armstrong(num):
  digitsum = 0
  temp = num
  # getting length of number
  no_of_digits = len(str(num))
  while temp != 0:
    digit = temp % 10
    # sum digit raise to the power of no of digits
    digitsum += (digit ** no_of_digits)
    temp = temp // 10
  print('Sum of digits is',  digitsum)
  # if sum and original number equal then Armstrong number
  return True if (digitsum == num) else False

num = int(input('Enter a number: '))
flag = check_armstrong(num)
if flag:
  print(num, 'is an Armstrong number')
else:
  print(num, 'is not an Armstrong number')

Output

Enter a number: 371
Sum of digits is 371
371 is an Armstrong number

Enter a number: 12345
Sum of digits is 4425
12345 is not an Armstrong number

Enter a number: 54748
Sum of digits is 54748
54748 is an Armstrong number

That's all for this topic Python Program to Check Armstrong Number. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Check Prime Number
  2. Python Program to Display Fibonacci Series
  3. Python Program to Count Occurrences of Each Character in a String
  4. Python continue Statement With Examples
  5. String Slicing in Python

You may also like-

  1. Name Mangling in Python
  2. Python Generator, Generator Expression, Yield Statement
  3. Constructor in Python - __init__() function
  4. Multiple Inheritance in Python
  5. ArrayList in Java With Examples
  6. Callable And Future in Java Concurrency
  7. Nested Class And Inner Class in Java
  8. Spring MessageSource Internationalization (i18n) Support

Saturday, December 3, 2022

Ternary Operator in Python

In Python there is no ternary operator in the form of (:?) as in programming languages like c, c++, Java. Python ternary operator is an if-else conditional expression written in a single line.

Form of Python ternary operator

Syntax for Python Ternary Operator is as given below-

[when_expr_true] if [conditional_expression] else [when_expr_false]

Initially conditional_expression is evaluated, if it is true then the ‘when_expr_true’ value is used, if false then ‘when_expr_false’ value is used.

Python ternary operator example

Let’s see an example to clarify the ternary operator usage. Here is a condition written using traditional if-else statement.

    if age > 18:
        msg = 'can vote'
    else:
        msg = "can't vote"
    print(msg)

Using ternary operator same condition can be written in one line as-

msg = 'can vote' if age > 18 else "can't vote"

As you can see using Python ternary operator you can test condition in a single line making the code concise and more readable. That’s the advantage of using ternary operator.

Nested Python ternary operator

Ternary operator can be nested too but beware that with nested ternary operators you lose the very advantage for which you tend to use ternary operator; readability.

For example following if-elif suite

  if a > b:
      print('a is greater than b')
  elif a < b:
      print('a is less than b')
  else:
      print('a and b are equal')

can be written using nested ternary operator-

msg = 'a is greater than b' if(a > b) else 'a is less than b' if(a < b) else 'a and b are equal'

Using ternary operator with tuple, dictionary

There is also a short form to be used with tuple and dictionary based on the fact that conditional_expression is evaluated first.

1. Consider the following example for tuple.

def display_msg(age):
    print('Age is', age)
    t = ("can't vote", "can vote")
    msg = t[age > 18]
    print(msg)


display_msg(20)
display_msg(8)

Output

Age is 20
can vote
Age is 8
can't vote

As you can see false value is stored first in the tuple and then the true value. It is because of the fact that false = 0 and true = 1. Expression t[age > 18] evaluates to t[0] if expression is false and it evaluates to t[1] if expression is true.

2. For dictionary you can store key value pair for true and false.

def display_msg(age):
    print('Age is', age)
    d = {True: "can vote", False: "can't vote"}
    msg = d[age > 18]
    print(msg)


display_msg(20)
display_msg(8)

Output

Age is 20
can vote
Age is 8
can't vote

That's all for this topic Ternary Operator in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Python for Loop With Examples
  2. pass Statement in Python
  3. Python First Program - Hello World
  4. Class And Object in Python
  5. self in Python

You may also like-

  1. Python Exception Handling Tutorial
  2. Abstract Class in Python
  3. Strings in Python With Method Examples
  4. Python Program to Count Occurrences of Each Character in a String
  5. Transaction Management in Java-JDBC
  6. Java Stream flatMap() Method
  7. Marker Interface in Java
  8. How to Create PDF in Java Using OpenPDF

Friday, August 26, 2022

Python Program to Find Factorial of a Number

In this post we’ll see how to write a Python program to find factorial of a number.

Factorial of a non-negative integer n is product of all positive integers from 1 to n. For example factorial of 4 can be calculated as-

4! = 4 X 3 X 2 X 1 = 24

Factorial program is one of the first program you'll write to understand recursive function so naturally in this post you'll see python program for factorial using recursion apart from writing using its iterative counterpart.

There is also an inbuilt function in Python for calculating factorial.

1. Recursive program to find factorial. In a recursive function you should have a base case to exit the repeated calling of the same function. In case of factorial program that base case is when num is 1.

def factorial(num):
  # base case(exit recursion)
  if num == 0 or num == 1:
    return 1
  else:
    return num * factorial(num - 1);

num = int(input('Enter a number- '))
print(factorial(num))

Output

Enter a number- 6
720

2. Iterative program to find factorial. Here for loop is used to iterate the passed number until it becomes 1, decrementing by 1 in each pass.

def factorial(num):
  fact = 1
  if num < 0:
    print('Please enter non-negative number')
  else:
    for i in range(num, 1, -1):
      fact = fact * i
    print('Factorial is- ', fact)

num = int(input('Enter a number- '))
factorial(num)

Output

Enter a number- -4
Please enter non-negative number

Enter a number- 0
Factorial is-  1

Enter a number- 4
Factorial is-  24

3. Using factorial function of the math module in Python. Import math module and use math.factorial() function to find factorial of a number.

import math

def factorial(num):
  print('Factorial is- ', math.factorial(num))

num = int(input('Enter a number- '))
factorial(num)

Output

Enter a number- 7
Factorial is-  5040

That's all for this topic Python Program to Find Factorial of a Number. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Programs Page


Related Topics

  1. Python Program to Display Fibonacci Series
  2. Python Program to Count Occurrences of Each Character in a String
  3. Python Conditional Statement - if, elif, else Statements
  4. Python return Statement With Examples
  5. String Slicing in Python

You may also like-

  1. Python Exception Handling Tutorial
  2. Class And Object in Python
  3. Removing Spaces From String in Python
  4. Fibonacci Series Program in Java
  5. Buffered Streams in Java IO
  6. DatabaseMetaData Interface in Java-JDBC
  7. Array in Java With Examples
  8. Spring Web Reactive Framework - Spring WebFlux Tutorial