Python slice 2d array – How to Slice Multidimensional Array in Python?

How to Slice Multidimensional Array in Python

Python slice 2d array: We’ve all heard about arrays, which are the simplest way to deal with a big number of the same data type. Arrays are much easier to work with and give us with a variety of features. For example, if you need to store a large quantity of data, you will almost certainly use an array rather than manually building a list. A multi-dimensional array is one that has many rows and columns.

What is slicing?

How to slice an array in python: In Python, slicing implies taking elements from one index to another i.e a part of the string, list, etc.

We use slice instead of index, as seen below: [start:end].

We can alternatively specify the step as [start:end:step].

The start index is where you want to start, the end index is where you want to stop, and the jump index is where you want to skip certain indices between the start and stop.

If we don’t pass start, it’s assumed to be 0.

If we do not pass the end, the length of the array in that dimension is assumed.

If we do not pass the step, it is assumed to be 1.

Let us now see the slicing of a multi-Dimensional Array.

Slice Multidimensional Array in Python

1) Creating a multi-Dimensional Array:

Approach:

  • Import numpy module using the import keyword.
  • Pass a list of lists(multi-dimensional array) to the array() function of the numpy module to create a multidimensional array.
  • Print the given array.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword.
import numpy as np
# Pass list of lists(multi-dimensional array) to the array() function
# of the numpy module to create a multi-dimensional array
gvn_arry =np.array([[10, 20, 30, 40, 50],[15, 25, 35, 45, 55]])
# Print the given array
print("The given array is:")
print(gvn_arry)

Output:

The given array is:
[[10 20 30 40 50]
 [15 25 35 45 55]]

2)Slicing the Array to get the first row:

# Printing the first row of the given array
print(gvn_arry[0][:])

Output:

[10 20 30 40 50]

3)Slicing the Array to get the second row:

# Printing the second row of the given array
print(gvn_arry[1][:])

Output:

[15 25 35 45 55]

4)Slicing the Array to get Alternate elements:

# Printing alternate elements of the given array
print(gvn_arry[::, ::2])

Output:

[[10 30 50]
 [15 35 55]]

5) Removing the start, end elements:

# Removing the start, end elements of the given multidimensional array
print(gvn_arry[:, 1:-1])

Output:

[[20 30 40]
 [25 35 45]]

6) Printing the elements of second-row index 1 to index 5(not included):

# Printing the elements of second row index 1 to index 5(not included):
print(gvn_arry[1, 1:5])

Output:

[25 35 45 55]

7) Creating a 3-Dimensional Array:

# Import numpy module using the import keyword.
import numpy as np
# Pass list of lists(multi-dimensional array) to the array() function
# of the numpy module to create a multi-dimensional array
# Here we create a 3D array.
gvn_arry =np.array([[10, 20, 30],[15, 25, 35], [50, 60, 70]])
# Print the given 3D array
print("The given 3D array is:")
print(gvn_arry)

Output:

The given 3D array is:
[[10 20 30]
 [15 25 35]
 [50 60 70]]

Entire Code:

# Import numpy module using the import keyword.
import numpy as np
# Pass list of lists(multi-dimensional array) to the array() function
# of the numpy module to create a multi-dimensional array
gvn_arry =np.array([[10, 20, 30, 40, 50],[15, 25, 35, 45, 55]])
# Print the given array
print("The given array is:")
print(gvn_arry)
print()
# Printing the first row of the given array
print(gvn_arry[0][:])
print()
# Printing the second row of the given array
print(gvn_arry[1][:])
print()
# Printing alternate elements of the given array
print(gvn_arry[::, ::2])
print()
# Removing the start, end elements of the given multidimensional array
print(gvn_arry[:, 1:-1])
print()
# Printing the elements of second row index 1 to index 5(not included):
print(gvn_arry[1, 1:5])

Output:

The given array is:
[[10 20 30 40 50]
[15 25 35 45 55]]

[10 20 30 40 50]

[15 25 35 45 55]

[[10 30 50]
[15 35 55]]

[[20 30 40]
[25 35 45]]

[25 35 45 55]

Python numpy mean – Python NumPy mean() Function

Python NumPy mean() Function

NumPy mean() Function:

Python numpy mean: The arithmetic mean along the provided axis is computed using the mean() function of the NumPy module. By default, the mean is calculated over the flattened array; otherwise, it is calculated over the given axis.

Syntax:

numpy.mean(a, axis=None, dtype=None, out=None, keepdims=<no value>)

Parameters

a: This is required. It is an array of numbers whose mean is to be computed. A conversion is attempted if “a” is not an array.

axis: This is optional. Indicate which axis or axes will be used to determine the mean. The default, axis=None, computes the flattened array’s mean.

dtype: This is optional. Indicate the data type that will be used to calculate the mean. The default for integer inputs is float64. It is the same as the input dtype for floating point inputs.

out: This is optional. It Indicates the output array for the result.  None is the default value. It must have the same shape as output if it is provided.

keepdims: This is optional. The reduced axes are left in the output as dimensions with size one if this is set to True. The result will broadcast correctly against the input array if you use this option. The keepdims will not be passed through to the mean function of ndarray sub-classes if the default value is used, but any non-default value will. Exceptions will be thrown if the sub-class method does not implement keepdims.

NumPy mean() Function in Python

Example1

Approach:

  • Import numpy module using the import keyword
  • Pass some random list as an argument to the array() function to create an array.
  • Store it in a variable.
  • Print the above-given array.
  • Pass the given array as an argument to the mean() function of numpy module to calculate the mean of all values in the given array
  • Store it in another variable.
  • Print the mean of all values in the given array.
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([[5,20],[35, 40]])              
# Print the above given array.
print("The above given array is:")
print(gvn_arry)
# Pass the given array as an argument to the mean() function of numpy module 
# to calculate the mean of all values in the given array 
# Store it in another variable.
rslt = np.mean(gvn_arry)
# Print the mean of all values in the given array 
print("The mean of all values in the given array =", rslt)

Output:

The above given array is:
[[ 5 20]
 [35 40]]
The mean of all values in the given array = 25.0

Example2

The mean is calculated over the specified axes when the axis parameter is set.

Approach:

  • Import numpy module using the import keyword
  • Pass some random list as an argument to the array() function to create an array.
  • Store it in a variable.
  • Print the above-given array.
  • Pass the given array, axis=0 as the arguments to the mean() function of numpy module to calculate the mean of all values in the given array along axis=0.
  • Store it in another variable.
  • Print the mean of all values the given array along axis=0
  • Pass the given array, axis=0 as the arguments to the mean() function of numpy module to calculate the mean of all values in the given array along axis=1.
  • Store it in another variable.
  • Print the mean of all values the given array along axis=1
  • The Exit of the Program.

Below is the implementation:

# Import numpy module using the import keyword
import numpy as np
# Pass some random list as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([[5, 25, 50],[35, 40, 60]])              
# Print the above given array.
print("The above given array is:")
print(gvn_arry)
# Pass the given array, axis=0 as the arguments to the mean() function of numpy module 
# to calculate the mean of all values in the given array along axis=0
# Store it in another variable.
rslt_1 = np.mean(gvn_arry, axis=0)
# Print the mean of all values the given array along axis=0
print("The mean of all values in the given array along axis=0: ", rslt_1)
# Pass the given array, axis=1 as the arguments to the mean() function of numpy module 
# to calculate the mean of all values in the given array along axis=1
# Store it in another variable.
rslt_2 = np.mean(gvn_arry, axis=1)
# Print the mean of all values the given array along axis=1
print("The mean of all values in the given array along axis=1: ", rslt_2)

Output:

The above given array is:
[[ 5 25 50]
[35 40 60]]
The mean of all values in the given array along axis=0: [20. 32.5 55. ]
The mean of all values in the given array along axis=1: [26.66666667 45. ]

Example3

The dtype argument can be used to retrieve the specific data type for the output.

# Import numpy module using the import keyword
import numpy as np
# Pass some random list as an argument to the array() function to
# create an array. 
# Store it in a variable.
gvn_arry = np.array([[5, 25, 50],[35, 40, 60]])              
# Print the above given array.
print("The above given array is:")
print(gvn_arry)
# Pass the given array, axis=0 and dtype=complex as the argument to the mean() function
# of numpy module to calculate the mean of all values in the given array
# along axis=0 and datatype as complex and print the result.
print("The mean of all values in the given array along axis=0 and datatype as complex =")
print(np.mean(gvn_arry, axis=0, dtype=complex))

Output:

The above given array is:
[[ 5 25 50]
[35 40 60]]
The mean of all values in the given array along axis=0 and datatype as complex =
[20. +0.j 32.5+0.j 55. +0.j]

Count rows in pandas – Pandas : count rows in a dataframe | all or those only that satisfy a condition

Count all rows or those that satisfy some condition in Pandas dataframe

Count rows in pandas: In this article we are going to show you how to count number of all rows in a DataFrame or rows that satisfy given condition in it.

First we are going to create dataframe,

import pandas as pd
students = [('Ankit', 22, 'Up', 'Geu'),
           ('Ankita', 31, 'Delhi', 'Gehu'),
           ('Rahul', 16, 'Tokyo', 'Abes'),
           ('Simran', 41, 'Delhi', 'Gehu'),
           ('Shaurya', 33, 'Delhi', 'Geu'),
           ('Harshita', 35, 'Mumbai', 'Bhu' ),
           ('Swapnil', 35, 'Mp', 'Geu'),
           ('Priya', 35, 'Uk', 'Geu'),
           ('Jeet', 35, 'Guj', 'Gehu'),
           ('Ananya', 35, 'Up', 'Bhu')
            ]
details = pd.DataFrame(students, columns =['Name', 'Age','Place', 'College'],
          index =['a', 'b', 'c', 'd', 'e','f', 'g', 'i', 'j', 'k'])

print(details)

Output:

RESTART: C:/Users/HP/Desktop/dataframe.py
Name       Age   Place      College
a   Ankit         22     Up          Geu
b   Ankita       31    Delhi       Gehu
c    Rahul       16    Tokyo      Abes
d   Simran     41     Delhi      Gehu
e   Shaurya    33     Delhi      Geu
f    Harshita   35     Mumbai Bhu
g   Swapnil    35     Mp        Geu
i    Priya         35     Uk         Geu
j    Jeet          35     Guj        Gehu
k   Ananya     35    Up         Bhu

Now lets see some other methods to count the rows in dataframe.

Count all rows in a Pandas Dataframe using Dataframe.shape

Pandas count rows in dataframe: Dataframe.shape attribute gives a sequence of index or row labels

(Number_of_index, Number_of_columns)

Number of index basically means number of rows in the dataframe.Let’s use this to count number of rows in above created dataframe.

import pandas as pd
students = [('Ankit', 22, 'Up', 'Geu'),
           ('Ankita', 31, 'Delhi', 'Gehu'),
           ('Rahul', 16, 'Tokyo', 'Abes'),
           ('Simran', 41, 'Delhi', 'Gehu'),
           ('Shaurya', 33, 'Delhi', 'Geu'),
           ('Harshita', 35, 'Mumbai', 'Bhu' ),
           ('Swapnil', 35, 'Mp', 'Geu'),
           ('Priya', 35, 'Uk', 'Geu'),
           ('Jeet', 35, 'Guj', 'Gehu'),
           ('Ananya', 35, 'Up', 'Bhu')
            ]
details = pd.DataFrame(students, columns =['Name', 'Age','Place', 'College'],
          index =['a', 'b', 'c', 'd', 'e','f', 'g', 'i', 'j', 'k'])
numOfRows = details.shape[0]

print("Number of rows :",numOfRows)

Output:

RESTART: C:/Users/HP/Desktop/dataframe.py
Number of rows : 10

Count all rows in a Pandas Dataframe using Dataframe.index

Pandas dataframe count rows: Dataframe.index attribute gives a sequence of index or row labels.We can calculate the length of that sequence to find out the number of rows in the dataframe.

import pandas as pd
students = [('Ankit', 22, 'Up', 'Geu'),
           ('Ankita', 31, 'Delhi', 'Gehu'),
           ('Rahul', 16, 'Tokyo', 'Abes'),
           ('Simran', 41, 'Delhi', 'Gehu'),
           ('Shaurya', 33, 'Delhi', 'Geu'),
           ('Harshita', 35, 'Mumbai', 'Bhu' ),
           ('Swapnil', 35, 'Mp', 'Geu'),
           ('Priya', 35, 'Uk', 'Geu'),
           ('Jeet', 35, 'Guj', 'Gehu'),
           ('Ananya', 35, 'Up', 'Bhu')
            ]
details = pd.DataFrame(students, columns =['Name', 'Age','Place', 'College'],
          index =['a', 'b', 'c', 'd', 'e','f', 'g', 'i', 'j', 'k'])
numOfRows = len(details.index)
print('Number of Rows in dataframe : ' , numOfRows)

Output:

RESTART: C:/Users/HP/Desktop/dataframe.py

Number of rows : 10

Count rows in a Pandas Dataframe that satisfies a condition using Dataframe.apply()

Count rows in pandas: This function apply  to all the rows of a dataframe to find out if elements of rows satisfies a condition or not, Based on the result it returns a bool series.

import pandas as pd
students = [('Ankit', 22, 'Up', 'Geu'),
           ('Ankita', 31, 'Delhi', 'Gehu'),
           ('Rahul', 16, 'Tokyo', 'Abes'),
           ('Simran', 41, 'Delhi', 'Gehu'),
           ('Shaurya', 33, 'Delhi', 'Geu'),
           ('Harshita', 35, 'Mumbai', 'Bhu' ),
           ('Swapnil', 35, 'Mp', 'Geu'),
           ('Priya', 35, 'Uk', 'Geu'),
           ('Jeet', 35, 'Guj', 'Gehu'),
           ('Ananya', 35, 'Up', 'Bhu')
            ]
details = pd.DataFrame(students, columns =['Name', 'Age','Place', 'College'],
          index =['a', 'b', 'c', 'd', 'e','f', 'g', 'i', 'j', 'k'])
seriesObj = details.apply(lambda x: True if x['Age'] > 30 else False , axis=1)
numOfRows = len(seriesObj[seriesObj == True].index)
print('Number of Rows in dataframe in which Age > 30 : ', numOfRows)

Output:

RESTART: C:/Users/HP/Desktop/dataframe.py
Number of Rows in dataframe in which Age > 30 : 8

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

Read more Articles on Python Data Analysis Using Padas

Conclusion:

In this article we have seen different method to count rows in a dataframe  all or those  that satisfy a condition.

Happy learning guys.

Python move file to directory – Python : How to move files and Directories ?

How to move files and directories in python.

Python move file to directory: In python, shutil module offers various files related operations

Syntax- shutil.move(src, dst)

It accepts source and destination path and moves file or directory from source pointed as src to destination pointed as dst.

Move a file to an another directory :

Python move directory: We will pass source file in first parameter and destination file in second parameter as string. Some points to keep in view.

  • If there is no file in destination directory then a new file will be created with the same name.
  • If already exists a file with same name in destination directory, then the file will be overwritten.
  • If in destination path, the path is not valid not existed it will result in FileNotFoundError.
import shutil
cre_path = shutil.move('satya.txt', 'document')    
print(cre_path)
Output :
FileNotFoundError: [Errno 2] No such file or directory: 'saya.txt'

Move a file with a new name :

Python move files: If we pass a new name of file in destination path, it will reflect in source file as it will move to source file with new name.

  • If there was already existed file with same name, then the file will be overwritten.
  • If path doesn’t exist for destination path it will result in error.

 

import shutil
cre_path = shutil.move('satya.txt', 'document/sample.txt')
print(cre_path)
Output :
FileNotFoundError: [Errno 2] No such file or directory: 'satya.txt'

Move all files in a directory to an another directory recursively :

Move files python: Let there is a situation where we want move all the files form one directory to another directory. To implement this, using shtil.move(), we will iterate all files in source directory and move each file to destination directory.

import shutil,os,glob
def mov_every_Files_Dir(sourDir, destDir):
    print(sourDir)
    print(destDir)
    # checking if both the are directories are not
    if os.path.isdir(sourDir) and os.path.isdir(destDir) :
        # Iterate through all the files in source directory
        for filePath in glob.glob(sourDir + '/*'):
            # moving the files to destination directory
            print(file_path)
            shutil.move(file_path, destDir);
    else:
        print("srcDir & dstDir should be Directories")   
def main():        
    if __name__ == '__main__':
        main()
    srcDir = '/users/sjones/chem/notes'
    desDir =  '/users/sjones/chem/notes_backup'
    mov_every_Files_Dir(srcDir,desDir)

Move file and Create Intermediate directories :

                We know that if there is no directory in a given path, then shutil.move() will give error. So we will create a function which move the file to destination directory and also create all directories in given path.

import shutil, os, glob
def moven_cre_Dir(srcPath, destDir):
    if os.path.isdir(destDir) == False:
        os.makedirs(destDir); 
    shutil.move(srcPath, destDir);
def main():
    if __name__ == '__main__':
        main()
    moven_cre_Dir(srcDir, destDir)
    srcFile = 'certificate/document.txt'
    destDir =  'certificate/document9'

Move symbolic links :

If source file is a symbolic link, then a link will be created at destination path that will point to source link and subsequently source link will be deleted.

Move a directory to an another directory :

We can move an entire directory to other locations by keeping a view on some points.

import shutil
sour_dir = 'satya'
dest_dir =  'satya1'
shutil.move(sour_dir, dest_dir)
Output :
FileNotFoundError: [Errno 2] No such file or directory: 'satya'
  • If there was already a destination directory, then source directory will move to destination directory.
  • If destination directory is not there, then it will be created.
  • If there is no intermediate directory or path is invalid then there will be error.
  • If there is another directory with same name as that of the source in the destination directory, then there also will be error.

 

 

 

Pandas to_list – Pandas: Convert a dataframe column into a list using Series.to_list() or numpy.ndarray.tolist() in python

Get a list of a specified column of a Pandas DataFrame

Pandas to_list: This article is all about how to get a list of a specified column of a Pandas DataFrame using different methods.

Lets create a dataframe which we will use in this article.

import pandas as pd 
students = [('juli', 34, 'Sydney', 155),
           ('Ravi', 31, 'Delhi', 177.5),
           ('Aaman', 16, 'Mumbai', 81),
           ('Mohit', 31, 'Delhi', 167),
           ('Veena', 12, 'Delhi', 144),
           ('Shan', 35, 'Mumbai', 135),
           ('Sradha', 35, 'Colombo', 111)
           ]

student_df = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])
print(student_df)

Output:

        Name    Age   City             Score
0      Julie      34     Sydney         155.0
1     Ravi       31      Delhi            177.5
2     Aman    16     Mumbai         81.0
3     Mohit    31     Delhi             167.0
4     Veena    12     Delhi             144.0
5      Shan     35    Mumbai         135.0
6     Sradha   35   Colombo        111.0

Now we are going to fetch a single column

There are different ways to do that.

using Series.to_list()

Numpy ndarray to dataframe: We will use the same example we use above in this article.We select the column ‘Name’ .We will use [] that gives a series object.Series.to_list()  this function we use provided by the Series class to convert the series object and return a list.

import pandas as pd 
students = [('juli', 34, 'Sydney', 155),
           ('Ravi', 31, 'Delhi', 177.5),
           ('Aaman', 16, 'Mumbai', 81),
           ('Mohit', 31, 'Delhi', 167),
           ('Veena', 12, 'Delhi', 144),
           ('Shan', 35, 'Mumbai', 135),
           ('Sradha', 35, 'Colombo', 111)
           ]

student_df = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])
list_of_names = student_df['Name'].to_list()
print('List of Names: ', list_of_names)
print('Type of listOfNames: ', type(list_of_names))

Output:

RESTART: C:/Users/HP/Desktop/article2.py
List of Names: ['juli', 'Ravi', 'Aaman', 'Mohit', 'Veena', 'Shan', 'Sradha']
Type of listOfNames: <class 'list'>

So in above example you have seen its working…let me explain in brief..

We have first select the column ‘Name’ from the dataframe using [] operator,it returns a series object names, and we have confirmed that by printing its type.

We used [] operator that gives a series object.Series.to_list()  this function we use provided by the series class to convert the series object and return a list.

This is how we converted a dataframe column into a list.

using numpy.ndarray.tolist()

From the give dataframe we will select the column “Name” using a [] operator that returns a Series object and uses

Series.Values to get a NumPy array from the series object. Next, we will use the function tolist() provided by NumPy array to convert it to a list.

import pandas as pd 
students = [('juli', 34, 'Sydney', 155),
           ('Ravi', 31, 'Delhi', 177.5),
           ('Aaman', 16, 'Mumbai', 81),
           ('Mohit', 31, 'Delhi', 167),
           ('Veena', 12, 'Delhi', 144),
           ('Shan', 35, 'Mumbai', 135),
           ('Sradha', 35, 'Colombo', 111)
           ]

student_df = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])
list_of_names = student_df['Name'].values.tolist()
print('List of Names: ', list_of_names)
print('Type of listOfNames: ', type(list_of_names))

Output:

RESTART: C:/Users/HP/Desktop/article2.py
List of Names: ['juli', 'Ravi', 'Aaman', 'Mohit', 'Veena', 'Shan', 'Sradha']
Type of listOfNames: <class 'list'>
>>>

So now we are going to show you its working,

We converted the column ‘Name’ into a list in a single line.Select the column ‘Name’ from the dataframe using [] operator,

From Series.Values get a Numpy array

import pandas as pd 
students = [('juli', 34, 'Sydney', 155),
           ('Ravi', 31, 'Delhi', 177.5),
           ('Aaman', 16, 'Mumbai', 81),
           ('Mohit', 31, 'Delhi', 167),
           ('Veena', 12, 'Delhi', 144),
           ('Shan', 35, 'Mumbai', 135),
           ('Sradha', 35, 'Colombo', 111)
           ]

student_df = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])
names = student_df['Name'].values
print('Numpy array: ', names)
print('Type of namesAsNumpy: ', type(names))

Output:

Numpy array: ['juli' 'Ravi' 'Aaman' 'Mohit' 'Veena' 'Shan' 'Sradha']
Type of namesAsNumpy: <class 'numpy.ndarray'>

Numpy array provides a function tolist() to convert its contents to a list.

This is how we selected our column ‘Name’ from Dataframe as a Numpy array and then turned it to a list.

Conclusion:

In this article i have shown you that how to get a list of a specified column of a Pandas DataFrame using different methods.Enjoy learning guys.Thank you!

Python Program to Create a List of Tuples with the First Element as the Number and Second Element as the Square of the Number

Program to Create a List of Tuples with the First Element as the Number and Second Element as the Square of the Number

Tuples in Python:

How to get the first element of a tuple in python: Tuples are comma-separated sequences or collections of things. In many aspects, they are identical to lists, except that the elements cannot be modified after they are created. Tuples in Python, unlike lists, are immutable objects. They also employ parentheses rather than square brackets.

Lists in Python:

Get second element of tuple python: A list is exactly what it sounds like: a container for various Python objects such as integers, words, values, and so on. In other programming languages, it is equal to an array. It is denoted with square brackets (and this is one of the attributes that differentiates it from tuples, which are separated by parentheses). It is also mutable, which means it can be changed or altered, as opposed to tuples, which are immutable.

Given lower limit range and upper limit range the task is to Make a list of Tuples with the first element being the number and the second element being the square of the number.

Examples:

Example1:

Input:

Enter some random lower limit =5
Enter some random lower limit =13

Output:

The list of Tuples are :  [(5, 25), (6, 36), (7, 49), (8, 64), (9, 81), (10, 100), (11, 121), (12, 144), (13, 169)]

Example2:

Input:

Enter some random lower limit =23
Enter some random lower limit =69

Output:

The list of Tuples are :  [(23, 529), (24, 576), (25, 625), (26, 676), (27, 729), (28, 784), (29, 841), (30, 900), (31, 961), 
(32, 1024), (33, 1089), (34, 1156), (35, 1225), (36, 1296), (37, 1369), (38, 1444), (39, 1521), (40, 1600), (41, 1681), 
(42, 1764), (43, 1849), (44, 1936), (45, 2025), (46, 2116), (47, 2209), (48, 2304), (49, 2401), (50, 2500), (51, 2601),
(52, 2704), (53, 2809), (54, 2916), (55, 3025), (56, 3136), (57, 3249), (58, 3364), (59, 3481), (60, 3600), (61, 3721),
(62, 3844), (63, 3969), (64, 4096), (65, 4225), (66, 4356), (67, 4489), (68, 4624), (69, 4761)]

Make a list of Tuples with the first element being the number and the second element being the square of the number in Python

There are several ways to create a list of tuples with the first element being the number and the second element being square of the given number some of them are:

Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.

Method 1:Using list comprehension (Static input)

Approach:

  • Give the lower limit range and upper limit range as static input.
  • Using list comprehension, generate a list of tuples with the first element being the number within the range and the second element being the square of the number.
  • The list of tuples will be printed.
  • Exit of program.

Below is the implementation:

# given lower limit range as static input
lowerlimit = 5
# given upper limit range as static input
upperlimit = 13
# Using list comprehension, generate a list of tuples with the first element being the number within
# the range and the second element being the square of the number.
listOfTuples = [(k, k**2) for k in range(lowerlimit, upperlimit+1)]
# printing the list of tuples
print('The list of Tuples are : ', listOfTuples)

Output:

The list of Tuples are :  [(5, 25), (6, 36), (7, 49), (8, 64), (9, 81), (10, 100), (11, 121), (12, 144), (13, 169)]

Explanation:

List comprehension must be used to produce a list of tuples in which the first element is the supplied range’s number and the second element is a square of the first number.

Method 2:Using list comprehension (User input)

Approach:

  • Scan the lower limit range and upper limit range as user input using int(input()) which converts string to integer.
  • Using list comprehension, generate a list of tuples with the first element being the number within the range and the second element being the square of the number.
  • The list of tuples will be printed.
  • Exit of program.

Below is the implementation:

# Scan lower limit range as user input
lowerlimit = int(input("Enter some random lower limit ="))
# Scan upper limit range as user  input
upperlimit = int(input("Enter some random lower limit ="))
# Using list comprehension, generate a list of tuples with the first element being the number within
# the range and the second element being the square of the number.
listOfTuples = [(k, k**2) for k in range(lowerlimit, upperlimit+1)]
# printing the list of tuples
print('The list of Tuples are : ', listOfTuples)

Output:

Enter some random lower limit =11
Enter some random lower limit =49
The list of Tuples are : [(11, 121), (12, 144), (13, 169), (14, 196), (15, 225), (16, 256), (17, 289), (18, 324), (19, 361), 
(20, 400), (21, 441), (22, 484), (23, 529), (24, 576), (25, 625), (26, 676), (27, 729), (28, 784), (29, 841), (30, 900), (31, 961),
 (32, 1024), (33, 1089), (34, 1156), (35, 1225), (36, 1296), (37, 1369), (38, 1444), (39, 1521), (40, 1600), (41, 1681), 
(42, 1764), (43, 1849), (44, 1936), (45, 2025), (46, 2116), (47, 2209), (48, 2304), (49, 2401)]

Method 3:Using for loop and append() function (Static input)

Approach:

  • Give the lower limit range and upper limit range as static input.
  • Take a empty list.
  • Iterate from lower limit range to upper limit range using for loop
  • Add iterate value and square of iterator value to the list as tuple using append() function.
  • The list of tuples will be printed.
  • Exit of program.

Below is the implementation:

# given lower limit range as static input
lowerlimit = 23
# given upper limit range as static input
upperlimit = 69
# Taking a empty list
listOfTuples = []
# using for loop
for value in range(lowerlimit, upperlimit+1):
    # adding number and square of the iterator value
    listOfTuples.append((value, value**2))

listOfTuples = [(k, k**2) for k in range(lowerlimit, upperlimit+1)]
# printing the list of tuples
print('The list of Tuples are : ', listOfTuples)

Output:

The list of Tuples are :  [(23, 529), (24, 576), (25, 625), (26, 676), (27, 729), (28, 784), (29, 841), (30, 900), (31, 961), 
(32, 1024), (33, 1089), (34, 1156), (35, 1225), (36, 1296), (37, 1369), (38, 1444), (39, 1521), (40, 1600), (41, 1681), 
(42, 1764), (43, 1849), (44, 1936), (45, 2025), (46, 2116), (47, 2209), (48, 2304), (49, 2401), (50, 2500), (51, 2601),
(52, 2704), (53, 2809), (54, 2916), (55, 3025), (56, 3136), (57, 3249), (58, 3364), (59, 3481), (60, 3600), (61, 3721),
(62, 3844), (63, 3969), (64, 4096), (65, 4225), (66, 4356), (67, 4489), (68, 4624), (69, 4761)]

Related Programs:

Python numpy.flatten() Function Tutorial with Examples | How to Use Function Numpy Flatten in Python?

Python numpy.flatten() Function Tutorial with Examples

Python flatten 2d array: In this tutorial, Beginners and Experience python developers will learn about function numpy.flatten(), how to use it, and how it works. Kindly, hit on the available links and understand how numpy.ndarray.flatten() function in Python gonna help you while programming.

numpy.ndarray.flatten() in Python

A numpy array has a member function to flatten its contents or convert an array of any shape to a 1D numpy array,

Syntax:

ndarray.flatten(order='C')

Parameters:

Here we can pass the following parameters-

Order: In this, we give an order in which items from the numpy array will be used,

C: Read items from array row-wise

F: Read items from array column-wise

A: Read items from array-based on memory order

Returns:

It returns a copy of the input array but in a 1D array.

Also Check:

Let’s learn the concept by viewing the below practical examples,

Flatten a matrix or a 2D array to a 1D array using ndarray.flatten()

First of all, import the numpy module,

import numpy as np

Let’s suppose, we have a 2D Numpy array,

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
print(arr_2d)

Output:

[7 4 2]
[5 4 3]
[9 7 1]]

Now we are going to use the above 2D Numpy array to convert the 1D Numpy array.

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
print(arr_2d)
# Convert the 2D array to 1D array
flat_array = arr_2d.flatten()
print('Flattened 1D Numpy Array:')
print(flat_array)

Output:

[[7 4 2]
[5 4 3]
[9 7 1]]

Flattened 1D Numpy Array:
[7 4 2 5 4 3 9 7 1]

So in the above example, you have seen how we converted the 2D array into a 1D array.

ndarray.flatten() returns a copy of the input array

flatten() function always returns a copy of the given array means if we make any changes in the returned array will not edit anything in the original one.

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
print(arr_2d)
flat_array = arr_2d.flatten()
flat_array[2] = 50
print('Flattened 1D Numpy Array:')
print(flat_array)
print('Original 2D Numpy Array')
print(arr_2d)

output:

[[7 4 2]
[5 4 3]
[9 7 1]]

Flattened 1D Numpy Array:
[ 7 4 50 5 4 3 9 7 1]

Original 2D Numpy Array
[[7 4 2]
[5 4 3]
[9 7 1]]

Thus in the above example, you can see that it has not affected the original array.

Flatten a 2D Numpy Array along Different Axis using flatten()

It accepts different parameter orders. It can be ‘C’ or ‘F’ or ‘A’, but the default value is ‘C’.
It tells the order.

  • C’: Read items from array row-wise i.e. using C-like index order.
  • ‘F’: Read items from array column-wise i.e. using Fortran-like index order.
  • ‘A’: Read items from an array on the basis of memory order of items.

In the below example, we are going to use the same 2D array which we used in the above example-

Flatten 2D array row-wise

In this, if we will not pass any parameter in function then it will take ‘C’ as a default value

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
flat_array = arr_2d.flatten(order='C')
print('Flattened 1D Numpy Array:')
print(flat_array)

Output:

Flattened 1D Numpy Array:
[7 4 2 5 4 3 9 7 1]

Flatten 2D array column-wise

If we pass ‘F’ as the order parameter in  function then it means elements from a 2D array will be read column wise

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
flat_array = arr_2d.flatten(order='F')
print('Flattened 1D Numpy Array:')
print(flat_array)

Output:

Flattened 1D Numpy Array:
[7 5 9 4 4 7 2 3 1]

Flatten 2D array based on memory layout

Let’s create a transparent view of the given 2D array

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
# Create a transpose view of array
trans_arr = arr_2d.T
print('Transpose view of array:')
print(trans_arr)

Output:

Transpose view of array:
[[7 5 9]
[4 4 7]
[2 3 1]]

Now flatten this view was Row Wise,

import numpy as np

# Create a 2D Numpy array from list of list
arr_2d = np.array([[7, 4, 2],
                  [5, 4, 3],
                  [9, 7, 1]])
# Create a transpose view of array
trans_arr = arr_2d.T
flat_array = trans_arr.flatten(order='C')
print(flat_array )

Output:

[7 5 9 4 4 7 2 3 1]

Flatten a 3D array to a 1D numpy array using ndarray.flatten()

Let’s create a 3D numpy array,

import numpy as np

# Create a 3D Numpy array
arr = np.arange(12).reshape((2,3,2))
print('3D Numpy array:')
print(arr)

Output:

3D Numpy array:
[[[ 0 1]
[ 2 3]
[ 4 5]]

[[ 6 7]
[ 8 9]
[10 11]]]

Now we are going to flatten this 3D numpy array,

import numpy as np

# Create a 3D Numpy array
arr = np.arange(12).reshape((2,3,2))
# Convert 3D array to 1D
flat_array = arr.flatten()
print('Flattened 1D Numpy Array:')
print(flat_array)

Output:

Flattened 1D Numpy Array:
[ 0 1 2 3 4 5 6 7 8 9 10 11]

Flatten a list of arrays using numpy.ndarray.flatten()

Now, we have to create a list of arrays,

# Create a list of numpy arrays
arr = np.arange(5)
list_of_arr = [arr] * 5
print('Iterate over the list of a numpy array')
for elem in list_of_arr:
    print(elem)

Output:

Iterate over the list of a numpy array
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]
[0 1 2 3 4]

Now, its time to convert the above list of numpy arrays to a flat 1D numpy array,

# Convert a list of numpy arrays to a flat array
flat_array = np.array(list_of_arr).flatten()
print('Flattened 1D Numpy Array:')
print(flat_array)

Output:

Flattened 1D Numpy Array:
[0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4]

Flatten a list of lists using ndarray.flatten()

To perform this process, first, we have to create a 2D numpy array from a list of list and then convert that to a flat 1D Numpy array,

# Create a list of list
list_of_lists = [[1, 2, 3, 4, 5],
                 [1, 2, 3, 4, 5],
                 [1, 2, 3, 4, 5],
                 [1, 2, 3, 4, 5]]
# Create a 2D numpy array from a list of list and flatten that array
flat_array = np.array(list_of_lists).flatten()
print('Flattened 1D Numpy Array:')
print(flat_array)
# Convert the array to list
print('Flat List:')
print(list(flat_array))

Output:

Flattened 1D Numpy Array:
[1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5]
Flat List:
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5]

Hence, this is how we can use flatten() function in numpy.

Conclusion:

We hope this python tutorial, you have seen how to use function numpy.flatten() assist you all in needy times. Thank you! keep visiting our site frequently for updated concepts of python.

Python string to int conversion – How to Convert a Python String to int

Convert Python String to Int:

Python string to int conversion: To convert a string to integer in Python, use the int() function. This function takes two parameters: the initial string and the optional base to represent the data. In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.But use of the int() function is not the only way to do so. This type of conversion can also be done using thefloat() keyword, as a float value can be used to compute with integers.

Below is the list of possible ways to convert an integer to string in python:

1. Using int() function:

Syntaxint(string)

Example:

Using int() function

Output:

Using int() function output
As a side note, to convert to float, we can use float() in python:

Example:

use float() in python

Output:

use float() in python output
2. Using float() function:

We first convert to float, then convert float to integer. Obviously the above method is better (directly convert to integer).

Syntax: float(string)

Example:

Using-float-function

Output:

Using float() function output

If you have a decimal integer represented as a string and you want to convert the Python string to an int, then you just follow the above method (pass the string to int()), which returns a decimal integer.But By default, int() assumes that the string argument represents a decimal integer. If, however, you pass a hexadecimal string to int(), then you’ll see a ValueError

For value error

The error message says that the string is not a valid decimal integer.

When you pass a string to int(), you can specify the number system that you’re using to represent the integer. The way to specify the number system is to use base:

Now, int() understands you are passing a hexadecimal string and expecting a decimal integer.

Conclusion:

This article is all about how to convert python string to int.All methods are clearly explained here. Now I hope you’re comfortable with the ins and outs of converting a Python string to an int.

Pandas row to list – Pandas : Convert a DataFrame into a list of rows or columns in python | (list of lists)

Converting a DataFrame into a list of rows or columns in python | (list of lists)

Pandas row to list: In this article, we will discuss how we can convert a dataframe into a list, by converting each row or column into a list and creating a python lists from them.

Let’s first, create a dataframe,

import pandas as pd
#The List of Tuples
students = [('Arun', 23, 'Chennai', 127),
            ('Priya', 31, 'Delhi', 174.5),
            ('Ritik', 24, 'Mumbai', 181),
            ('Kimun', 37, 'Hyderabad', 125),
            ('Sinvee', 16, 'Delhi', 175.5),
            ('Kunu', 28, 'Mumbai', 115),
            ('Lisa', 31, 'Pune', 191)
            ]
# Creating DataFrame object
studentId = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])
print(studentId)
Output :
     Name     Age       City           Score
0    Arun      23     Chennai         127.0
1   Priya       31      Delhi            174.5
2   Ritik        24     Mumbai         181.0
3   Kimun     37    Hyderabad     125.0
4   Sinvee    16      Delhi              175.5
5    Kunu    28     Mumbai           115.0
6    Lisa      31       Pune              191.0

Convert a Dataframe into a list of lists – Rows Wise :

In the dataframe created above, we must fetch each line as a list and create a list of these lists.

Let’s see how we can do this

import pandas as pd
#The List of Tuples
students = [('Arun', 23, 'Chennai', 127),
            ('Priya', 31, 'Delhi', 174.5),
            ('Ritik', 24, 'Mumbai', 181),
            ('Kimun', 37, 'Hyderabad', 125),
            ('Sinvee', 16, 'Delhi', 175.5),
            ('Kunu', 28, 'Mumbai', 115),
            ('Lisa', 31, 'Pune', 191)
            ]
# Creating DataFrame object
studentId = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])

# By Converting a dataframe to the list of rows (list of lists)
listOfRows = studentId.to_numpy().tolist()
print(listOfRows)
print(type(listOfRows))
Output :
[['Arun', 23, 'Chennai', 127.0], ['Priya', 31, 'Delhi', 174.5], ['Ritik', 24, 'Mumbai', 181.0], ['Kimun', 37, 'Hyderabad', 125.0], ['Sinvee', 16, 'Delhi', 175.5], ['Kunu', 28, 'Mumbai', 115.0], ['Lisa', 31, 'Pune', 191.0]]
<class 'list'>

It Converted the data name into a sequential target list, that is, each linked list contains a line of data names. But what happened in one line ?

How did it work?

Let’s divide one line above into several lines to understand the concept behind it.

Step 1: Convert the Dataframe to a nested Numpy array using DataFrame.to_numpy() :

import pandas as pd
#The List of Tuples
students = [('Arun', 23, 'Chennai', 127),
            ('Priya', 31, 'Delhi', 174.5),
            ('Ritik', 24, 'Mumbai', 181),
            ('Kimun', 37, 'Hyderabad', 125),
            ('Sinvee', 16, 'Delhi', 175.5),
            ('Kunu', 28, 'Mumbai', 115),
            ('Lisa', 31, 'Pune', 191)
            ]
# Creating DataFrame object
studentId = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])


# By getting rows of a dataframe as a nested numpy array
numpy_2d_array = studentId.to_numpy()
print(numpy_2d_array)
print(type(numpy_2d_array))
Output :
[['Arun' 23 'Chennai' 127.0]
['Priya' 31 'Delhi' 174.5]
['Ritik' 24 'Mumbai' 181.0]
['Kimun' 37 'Hyderabad' 125.0]
['Sinvee' 16 'Delhi' 175.5]
['Kunu' 28 'Mumbai' 115.0]
['Lisa' 31 'Pune' 191.0]]
<class 'numpy.ndarray'>

Actually DataFrame.to_numpy() converts data name into Numpy array. So we have a 2D Numpy array here. We have confirmed that by printing the type of returned item.

Step 2: Convert 2D Numpy array into a list of lists :

Numpy provides a function tolist(), which converts Numpy Array into a list. Let’s call that function in the object built above 2D Numpy,

import pandas as pd
#The List of Tuples
students = [('Arun', 23, 'Chennai', 127),
            ('Priya', 31, 'Delhi', 174.5),
            ('Ritik', 24, 'Mumbai', 181),
            ('Kimun', 37, 'Hyderabad', 125),
            ('Sinvee', 16, 'Delhi', 175.5),
            ('Kunu', 28, 'Mumbai', 115),
            ('Lisa', 31, 'Pune', 191)
            ]
# Creating DataFrame object
studentId = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])


# By getting rows of a dataframe as a nested numpy array
numpy_2d_array = studentId.to_numpy()

# By Converting 2D numpy array to the list of lists
listOfRows = numpy_2d_array.tolist()
print(listOfRows)
print(type(listOfRows))
Output :
[['Arun', 23, 'Chennai', 127.0], ['Priya', 31, 'Delhi', 174.5], ['Ritik', 24, 'Mumbai', 181.0], ['Kimun', 37, 'Hyderabad', 125.0], ['Sinvee', 16, 'Delhi', 175.5], ['Kunu', 28, 'Mumbai', 115.0], ['Lisa', 31, 'Pune', 191.0]]
<class 'list'>

It converted 2D Numpy Array into a list.

So, this is how we changed the dataframe to 2D Numpy Array and then List of Lists, where each nested list represents a dataframe line.

Convert a Dataframe into a list of lists – Column Wise :

Now turn each column into a list and create a list of these lists,

import pandas as pd
#The List of Tuples
students = [('Arun', 23, 'Chennai', 127),
            ('Priya', 31, 'Delhi', 174.5),
            ('Ritik', 24, 'Mumbai', 181),
            ('Kimun', 37, 'Hyderabad', 125),
            ('Sinvee', 16, 'Delhi', 175.5),
            ('Kunu', 28, 'Mumbai', 115),
            ('Lisa', 31, 'Pune', 191)
            ]
# Creating DataFrame object
studentId = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])


# Convert a dataframe to the list of columns i.e. list of lists
listOfRows = studentId.transpose().values.tolist()
print(listOfRows)
print(type(listOfRows))
Output :
[['Arun', 'Priya', 'Ritik', 'Kimun', 'Sinvee', 'Kunu', 'Lisa'], [23, 31, 24, 37, 16, 28, 31], ['Chennai', 'Delhi', 'Mumbai', 'Hyderabad', 'Delhi', 'Mumbai', 'Pune'], [127.0, 174.5, 181.0, 125.0, 175.5, 115.0, 191.0]]

<class 'list'>

How did it work?

It works on the same concept we discussed above, just one more step here i.e.

Step 1: Transpose the dataframe to convert rows as columns and columns as rows :

import pandas as pd
#The List of Tuples
students = [('Arun', 23, 'Chennai', 127),
            ('Priya', 31, 'Delhi', 174.5),
            ('Ritik', 24, 'Mumbai', 181),
            ('Kimun', 37, 'Hyderabad', 125),
            ('Sinvee', 16, 'Delhi', 175.5),
            ('Kunu', 28, 'Mumbai', 115),
            ('Lisa', 31, 'Pune', 191)
            ]
# Creating DataFrame object
studentId = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])



# Transposing the dataframe, rows are now columns and columns are now rows
transposedObj = studentId.transpose()
print(transposedObj)

Output :
0      1       2          3       4       5      6
Name      Arun  Priya   Ritik      Kimun  Sinvee    Kunu   Lisa
Age         23     31      24         37      16      28     31
City   Chennai  Delhi  Mumbai  Hyderabad   Delhi  Mumbai   Pune
Score    127.0  174.5   181.0      125.0   175.5   115.0  191.0

transposedObj is a transpose of the original data i.e. lines in studentId with columns in transposedObj and columns in studentId are lines in transposedObj.

Step 2: Convert the Dataframe to a nested Numpy array using DataFrame.to_numpy() :

import pandas as pd
#The List of Tuples
students = [('Arun', 23, 'Chennai', 127),
            ('Priya', 31, 'Delhi', 174.5),
            ('Ritik', 24, 'Mumbai', 181),
            ('Kimun', 37, 'Hyderabad', 125),
            ('Sinvee', 16, 'Delhi', 175.5),
            ('Kunu', 28, 'Mumbai', 115),
            ('Lisa', 31, 'Pune', 191)
            ]
# Creating DataFrame object
studentId = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])


# Transposing the dataframe, rows are now columns and columns are now rows
transposedObj = studentId.transpose()


# By getting rows of a dataframe as a nested numpy array
numpy_2d_array = transposedObj.to_numpy()
print(numpy_2d_array)
print(type(numpy_2d_array))
Output :
[['Arun' 'Priya' 'Ritik' 'Kimun' 'Sinvee' 'Kunu' 'Lisa']
[23 31 24 37 16 28 31]
['Chennai' 'Delhi' 'Mumbai' 'Hyderabad' 'Delhi' 'Mumbai' 'Pune']
[127.0 174.5 181.0 125.0 175.5 115.0 191.0]]
<class 'numpy.ndarray'>

Step 3: Convert 2D Numpy array into a list of lists. :

import pandas as pd
#The List of Tuples
students = [('Arun', 23, 'Chennai', 127),
            ('Priya', 31, 'Delhi', 174.5),
            ('Ritik', 24, 'Mumbai', 181),
            ('Kimun', 37, 'Hyderabad', 125),
            ('Sinvee', 16, 'Delhi', 175.5),
            ('Kunu', 28, 'Mumbai', 115),
            ('Lisa', 31, 'Pune', 191)
            ]
# Creating DataFrame object
studentId = pd.DataFrame(students, columns=['Name', 'Age', 'City', 'Score'])


# Transposing the dataframe, rows are now columns and columns are now rows
transposedObj = studentId.transpose()


# By getting rows of a dataframe as a nested numpy array
numpy_2d_array = transposedObj.to_numpy()

#By Converting 2D numpy array to the list of lists
listOfRows = numpy_2d_array.tolist()
print(listOfRows)
print(type(listOfRows))
Output :
[['Arun', 'Priya', 'Ritik', 'Kimun', 'Sinvee', 'Kunu', 'Lisa'], [23, 31, 24, 37, 16, 28, 31], ['Chennai', 'Delhi', 'Mumbai', 'Hyderabad', 'Delhi', 'Mumbai', 'Pune'], [127.0, 174.5, 181.0, 125.0, 175.5, 115.0, 191.0]]
<class 'list'>

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

Read more Articles on Python Data Analysis Using Padas – Select items from a Dataframe

Print odd numbers in python – Python Program to Print Odd Numbers in Given Range Using Recursion

Program to Print Odd Numbers in Given Range Using Recursion

Print odd numbers in python: In the previous article, we have discussed Python Program to Print Even Numbers in Given Range Using Recursion

Given the upper limit and the task is to print the odd numbers in a given range (from 1 to given limit).

Recursion:

How to print odd numbers in python: Recursion is the process by which a function calls itself directly or indirectly, and the associated function is known as a recursive function. Certain issues can be addressed fairly easily using a recursive approach. Towers of Hanoi (TOH), Inorder /Preorder/Postorder Tree Traversals, DFS of Graph, and other analogous issues are examples.

Examples:

Example1:

Input:

 Given Upper Limit = 45

Output:

The Odd Numbers in a given range 1 and 45 are :
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45

Example2:

Input:

Given Upper Limit = 20

Output:

The Odd Numbers in a given range 1 and 20 are :
1 3 5 7 9 11 13 15 17 19

Program to Print Odd Numbers in Given Range Using Recursion in Python

Below are the ways to print the odd numbers in a given range in python:

Method #1: Using Recursion (Static Input)

Approach:

  • Give the lower limit as 1 and store it in a variable.
  • Give the upper limit as static input and store it in another variable.
  • Pass the given lower and upper limits as the arguments to the odd_range function.
  • Create a recursive function to say odd_range which takes the given lower and upper limits as arguments and returns the odd numbers in a given range using recursion.
  • Check if the given lower limit value is greater than the upper limit using the if conditional statement.
  • If the statement is true, then return.
  • After the return statement, print the given lower limit separated by spaces.
  • Return odd_range(gvnlowr_lmt+2, gvnuppr_lmt) {Recursive Logic}.
  • Print the Odd Numbers in a given lower and upper limit range.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say odd_range which takes the given lower and upper
# limits as arguments and returns the odd numbers in a given range using recursion.


def odd_range(gvnlowr_lmt, gvnuppr_lmt):
    # Check if the given lower limit value is greater than the upper limit using the if
    # conditional statement.
    if gvnlowr_lmt > gvnuppr_lmt:
        # If the statement is true, then return.
        return
    # After the return statement, print the given lower limit separated by spaces.
    print(gvnlowr_lmt, end=" ")
    # Return odd_range(gvnlowr_lmt+2, gvnuppr_lmt) {Recursive Logic}.
    return odd_range(gvnlowr_lmt+2, gvnuppr_lmt)


# Give the lower limit as 1 and store it in a variable.
gvnlowr_lmt = 1
# Give the upper limit as static input and store it in another variable.
gvnuppr_lmt = 45
# Pass the given lower and upper limits as the arguments to odd_range function.
# Print the Odd Numbers in a given range.
print("The Odd Numbers in a given range",
      gvnlowr_lmt, "and", gvnuppr_lmt, "are :")
odd_range(gvnlowr_lmt, gvnuppr_lmt)

Output:

The Odd Numbers in a given range 1 and 45 are :
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45

Method #2: Using Recursion (User Input)

Approach:

  • Give the lower limit as 1 and store it in a variable.
  • Give the upper limit as user input using the int(input()) function and store it in another variable.
  • Pass the given lower and upper limits as the arguments to the odd_range function.
  • Create a recursive function to say odd_range which takes the given lower and upper limits as arguments and returns the odd numbers in a given range using recursion.
  • Check if the given lower limit value is greater than the upper limit using the if conditional statement.
  • If the statement is true, then return.
  • After the return statement, print the given lower limit separated by spaces.
  • Return odd_range(gvnlowr_lmt+2, gvnuppr_lmt) {Recursive Logic}.
  • Print the Odd Numbers in a given lower and upper limit range.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say odd_range which takes the given lower and upper
# limits as arguments and returns the odd numbers in a given range using recursion.


def odd_range(gvnlowr_lmt, gvnuppr_lmt):
    # Check if the given lower limit value is greater than the upper limit using the if
    # conditional statement.
    if gvnlowr_lmt > gvnuppr_lmt:
        # If the statement is true, then return.
        return
    # After the return statement, print the given lower limit separated by spaces.
    print(gvnlowr_lmt, end=" ")
    # Return odd_range(gvnlowr_lmt+2, gvnuppr_lmt) {Recursive Logic}.
    return odd_range(gvnlowr_lmt+2, gvnuppr_lmt)


# Give the lower limit as 1 and store it in a variable.
gvnlowr_lmt = 1
# Give the upper limit as user input using the int(input()) function and
# store it in another variable.
gvnuppr_lmt = int(input("Enter some random number = "))
# Pass the given lower and upper limits as the arguments to odd_range function.
# Print the Odd Numbers in a given range.
print("The Odd Numbers in a given range",
      gvnlowr_lmt, "and", gvnuppr_lmt, "are :")
odd_range(gvnlowr_lmt, gvnuppr_lmt)

Output:

Enter some random number = 20
The Odd Numbers in a given range 1 and 20 are :
1 3 5 7 9 11 13 15 17 19

If you are new to the Python Programming Language then practice using our Python Programming Examples for Beginners as our expert team has designed them from scratch.