Python Tutorial

Introduction Python Features Python Applications Python System requirements Python Installation Python Examples Python Basics Python Indentation Python Variables Python Data Types Python IDE Python Keywords Python Operators Python Comments Python Pass Statement

Python Conditional Statements

Python if Statement Python elif Statement Python If-else statement Python Switch Case

Python Loops

Python for loop Python while loop Python Break Statement Python Continue Statement Python Goto Statement

Python Arrays

Python Array Python Matrix

Python Strings

Python Strings Python Regex

Python Built-in Data Structure

Python Lists Python Tuples Python Lists vs Tuples Python Dictionary Python Sets

Python Functions

Python Function Python min() function Python max() function Python User-define Functions Python Built-in Functions Python Recursion Anonymous/Lambda Function in Python apply() function in python Python lambda() Function

Python File Handling

Python File Handling Python Read CSV Python Write CSV Python Read Excel Python Write Excel Python Read Text File Python Write Text File Read JSON File in Python

Python Exception Handling

Python Exception Handling Python Errors and exceptions Python Assert

Python OOPs Concept

OOPs Concepts in Python Classes & Objects in Python Inheritance in Python Polymorphism in Python Python Encapsulation Python Constructor Python Super function Python Static Method Static Variables in Python Abstraction in Python

Python Iterators

Iterators in Python Yield Statement In Python Python Yield vs Return

Python Generators

Python Generator

Python Decorators

Python Decorator

Python Functions and Methods

Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods

Python Modules

Python Modules Python Datetime Module Python Math Module Python Import Module Python Time ModulePython Random Module Python Calendar Module CSV Module in Python Python Subprocess Module

Python MySQL

Python MySQL Python MySQL Client Update Operation Delete Operation Database Connection Creating new Database using Python MySQL Creating Tables Performing Transactions

Python MongoDB

Python MongoDB

Python SQLite

Python SQLite

Python Data Structure Implementation

Python Stack Python Queue Python Linked List Python Hash Table Python Graph

Python Advance Topics

Speech Recognition in Python Face Recognition in Python Python Linear regression Python Rest API Python Command Line Arguments Python JSON Python Subprocess Python Virtual Environment Type Casting in Python Python Collections Python Attributes Python Commands Python Data Visualization Python Debugger Python DefaultDict Python Enumerate

Python 2

What is Python 2

Python 3

Anaconda in Python 3 Anaconda python 3 installation for windows 10 List Comprehension in Python3

How to

How to Parse JSON in Python How to Pass a list as an Argument in Python How to Install Numpy in PyCharm How to set up a proxy using selenium in python How to create a login page in python How to make API calls in Python How to run Python code from the command prompt How to read data from com port in python How to Read html page in python How to Substring a String in Python How to Iterate through a Dictionary in Python How to convert integer to float in Python How to reverse a string in Python How to take input in Python How to install Python in Windows How to install Python in Ubuntu How to install PIP in Python How to call a function in Python How to download Python How to comment multiple lines in Python How to create a file in Python How to create a list in Python How to declare array in Python How to clear screen in Python How to convert string to list in Python How to take multiple inputs in Python How to write a program in Python How to compare two strings in Python How to create a dictionary in Python How to create an array in Python How to update Python How to compare two lists in Python How to concatenate two strings in Python How to print pattern in Python How to check data type in python How to slice a list in python How to implement classifiers in Python How To Print Colored Text in Python How to open a file in python How to Open a file in python with Path How to run a Python file in CMD How to change the names of Columns in Python How to Concat two Dataframes in Python How to Iterate a List in Python How to learn python Online How to Make an App with Python How to develop a game in python How to print in same line in python How to create a class in python How to find square root in python How to import numy in python How to import pandas in python How to uninstall python How to upgrade PIP in python How to append a string in python How to comment out a block of code in Python How to change a value of a tuple in Python How to append an Array in Python How to Configure Python Interpreter in Eclipse Parameter Passing in Python How to plot a Histogram in Python How to Import Files in Python How to Download all Modules in Python How to get Time in seconds in Python How to Practice Python Programming How to plot multiple linear regression in Python How to set font for Text in Python

Sorting

Python Sort List Sort Dictionary in Python Python sort() function Python Bubble Sort

Programs

Factorial Program in Python Prime Number Program in Python Fibonacci Series Program in Python Leap Year Program in Python Palindrome Program in Python Check Palindrome In Python Calculator Program in Python Armstrong Number Program in Python Python Program to add two numbers Anagram Program in Python Number Pattern Programs in Python Even Odd Program in Python GCD Program in Python Python Exit Program Python Program to check Leap Year Operator Overloading in Python Pointers in Python Python Not Equal Operator Raise Exception in Python Salary of Python Developers in India What is a Script in Python

Misc

Introduction to Scratch programming SKLearn Clustering SKLearn Linear Module Standard Scaler in SKLearn Python Time Library SKLearn Model Selection Standard Scaler in SKLearn Accuracy_score Function in Sklearn Append key Value to Dictionary in Python Cross Entropy in Python Cursor in Python Data Class in Python How to Install Tweepy in Python Imread Python Program of Cumulative Sum in Python Python Program for Linear Search Python Program to Generate a Random String Read numpy array in Python Scrimba python Sklearn linear Model in Python Scraping data in python Accessing Key-value in Dictionary in Python Find Median of List in Python Linear Regression using Sklearn with Example Problem-solving with algorithm and data structures using Python Python 2.7 data structures Python Variable Scope with Local & Non-local Examples Arguments and parameters in Python Assertion error in python Programs for Printing Pyramid Patterns in Python _name_ in Python Amazon rekognition using python Anaconda python 3.7 download for windows 10 64-bit Android apps for coding in python Augmented reality in python Best app for python Difference between Perl and Python Not supported between instances of str and int in python Python comment symbol Python Complex Class Python IDE names Selection Sort Using Python Hypothesis Testing in Python Idle python download for Windows Insertion Sort using Python Merge Sort using Python Python - Binomial Distribution Python Logistic Regression with Sklearn & Scikit Python Random shuffle() method Python variance() function Python vs HTML Removing the First Character from the String in Python Adding item to a python dictionary Best books for NLP with Python Best Database for Python Count Number of Keys in Dictionary Python Cross Validation in Sklearn Drop() Function in Python EDA in Python Excel Automation with Python Python Program to Find the gcd of Two Numbers Python Web Development projects Adding a key-value pair to dictionary in Python Python Euclidean Distance Python Filter List Python Fit Transform Python e-book free download Python email utils Python range() Function Python random.seed() function What is the re.sub() function in Python Python PPTX Python Pickle Python Seaborn Python Coroutine Python EOL Python Infinity Python math.cos and math.acos function Python Project Ideas Based On Django Reverse a String in Python Reverse a Number in Python Python Word Tokenizer Python Trigonometric Functions Python try catch exception GUI Calculator in Python Implementing geometric shapes into the game in python Installing Packages in Python Python Try Except Python Sending Email Socket Programming in Python Python CGI Programming Python Data Structures Python abstract class Python Compiler Python K-Means Clustering NSE Tools In Python Operator Module In Python Palindrome In Python Permutations in Python Pillow Python introduction and setup Python Functionalities of Pillow Module Python Argmin Python whois Python JSON Schema Python lock Return Statement In Python Reverse a sentence In Python tell() function in Python Why learn Python? Write Dictionary to CSV in Python Write a String in Python Binary Search Visualization using Pygame in Python Latest Project Ideas using Python 2022 Closest Pair of Points in Python ComboBox in Python Python vs R Best resources to learn Numpy and Pandas in python Check Letter in a String Python Python Console Python Control Statements Convert Float to Int in Python using Pandas Difference between python list and tuple Importing Numpy in Pycharm Python Key Error Python NewLine Python tokens and character set Python Strong Number any() Keyword in python Best Database in Python Check whether dir is empty or not in python Comments in the Python Programming Language Convert int to Float in Python using Pandas Decision Tree Classification in Python End Parameter in python __GETITEM__ and __SETITEM__ in Python Python Namespace Python GUI Programming List Assignment Index out of Range in Python List Iteration in Python List Index out of Range Python for Loop List Subtract in Python Python Empty Tuple Python Escape Characters Sentence to python vector Slicing of a String in Python Executing Shell Commands in Python Genetic Algorithm in python Get index of element in array in python Looping through Data Frame in Python Syntax of Map function in Python After Python What Should I Learn Python AIOHTTP Alexa Python Artificial intelligence mini projects ideas in python Artificial intelligence mini projects with source code in Python Find whether the given stringnumber is palindrome or not First Unique Character in a String Python Python Network Programming Python Interface Python Multithreading Python Interpreter Data Distribution in python Flutter with tensor flow in python Front end in python Iterate a Dictionary in Python Iterate a Dictionary in Python – Part 2 Allocate a minimum number of pages in python Assertion Errors and Attribute Errors in Python Checking whether a String Contains a Set of Characters in python Python Control Flow Statements *Args and **Kwargs in Python Bar Plot in Python Conditional Expressions in Python Function annotations() in Python How to Write a Configuration file in Python Image to Text in python import() Function in Python Import py file in Python Multiple Linear Regression using Python Nested Tuple in Python Python String Negative Indexing Reading a File Line by Line in Python Python Comment Block Base Case in Recursive function python ER diagram of the Bank Management System in python Image to NumPy Arrays in Python NOT IN operator in Python One Liner If-Else Statements in Python Sklearn in Python Cube Root in Python Python Variables, Constants and Literals What Does the Percent Sign (%) Mean in Python Creating Web Application in python Notepad++ For Python PyPi TensorFlow Python | Read csv using pandas.read_csv() What is online python free IDE What is Python online compiler Run exec python from PHP What are the Purposes of Python What is Python compiler GDB Python coding platform Python Classification Python | a += b is not always a = a + b PyDev with Python IDE Character Set in Python Best Python AI Projects _dict_ in Python Python Ternary Operators Self in Python Python vs Java Python Modulo Python Packages Python Syntax Python Uses Python Bitwise Operators Python Identifiers Python Matrix Multiplication Python AND Operator Python Logical Operators Python Multiprocessing Python Unit Testing __init__ in Python Advantages of Python Is Python Case-sensitive when Dealing with Identifiers Python Boolean Python Call Function Python History Python Image Processing Python main() function Python Permutations and Combinations Difference between Input() and raw_input() functions in Python Conditional Statements in python Confusion Matrix Visualization Python Nested List in Python Python Algorithms Python Modules List Difference between Python 2 and Python 3 Is Python Case Sensitive Method Overloading in Python Python Arithmetic Operators Assignment Operators in Python Is Python Object Oriented Programming language Python Division Python exit commands Continue And Pass Statements In Python Colors In Python Convert String Into Int In Python Convert String To Binary In Python Convert Uppercase To Lowercase In Python Convert XML To JSON In Python Converting Set To List In Python Covariance In Python CSV Module In Python Decision Tree In Python Difference Between Yield And Return In Python Dynamic Typing In Python BOTTLE Python Web Framework How to Install Scikit-Learn Introducing modern python computing in simple packages Python vs PHP Reason for Python So Popular Returning Multiple Values in Python Spotify API in Python Spyder (32-bit) - Free download Time. Sleep() in Python Traverse Dictionary in Python What is Ipython shell YOLO Python Nested for Loop in Python Data Structures and Algorithms Using Python | Part 1 Data Structures and Algorithms using Python | Part 2 ModuleNotFoundError No module named 'mysql' in Python N2 in Python XGBoost for Regression in Python Explain sklearn clustering in Python Data Drop in Python Falcon Python Flutter Python Google Python Class Excel to CSV in Python Google Chrome API in Python Gaussian elimination in python Matrix List Comprehension in Python Python List Size Python data science course StandardScaler in Sklearn Python Redis Example Python Program for Tower of Hanoi Python Printf Style Formating Python Percentage Sign Python Parse Text File Python Parallel Processing Python Online Compiler Python maketrans() function Python Loop through a Dictionary Python for Data Analysis Python for Loop Increment Python Kwargs Example Python Line Break

Commands in Python

In this tutorial, we will see some of the widely used python commands along with their syntaxes and examples. To make Python more user-friendly, developers have provided these commands to ease using the python language.

Now, let us move ahead with our topic.

1. Print command

To print any output, calculated result, or the specified text on the screen or even on other output devices, this print command is used. It can be used to print objects of types including string, tuple, integer, etc.

Syntax – print(object)

Here, the object refers to the text or the value the programmer wants to display.

Example: The following code illustrates the use of a print statement. Here, 4 different objects, i.e., int, string, list, and tuple are being printed.

#Program to understand the usage of print statements


# integer is being printed
x=78
print (x)


# string is being printed
print ("Bonjour, World!")


# list is being printed
l=[110, 34, 567, 321]
print(l)


# tupule is being printed
t= (13, 67)
            print(t)

Output:

Commands in Python

2. pip install command

It is a package manager command written in python. It is taken into account to install and manage the installed software packages. It can install any software packages from the python package index, a public repository available online.

Syntax – pip install package-name

Example: The following figure shows how to install any packages in python using the pip command. Here, pandas are being installed in Windows operating system.

Commands in Python

3. type command

To check the type or class of an object, the type command is taken into account.

Syntax: type(object)

Here, the object refers to the value whose type is to be checked.

Example: The following code illustrates the utility of type command. Here the objects - list, dictionary and tuple are taken into account.

# Python3 code to understand the utility of type() function
# Class of list	type
class ListType:
	ListNo = [16, 23, 38, 43, 59]
	# it Will print the object type of existing class ListType
	print(type(ListNo))


# Class of dict type
class DictType:
	DictNo = {1:'Computer', 2:'programming',
				3:'is', 4:'undoubtedly', 5: ‘interesting’}
	# It will print the object type of existing class DictType
	print(type(DictNo))


# Class of tuple type
class TupleType:
	TupleNo = ('Java', 'T', 'point', ‘learning’, ‘website’)
	# It will print the object type of existing class TupleType
	print(type(TupleNo))
# Creating object of each class	
d = DictType()
l = ListType()
t = TupleType()

Output:

Commands in Python

4. Input command

To take input from users, the input command is taken into account.

The flow continues as long as the user doesn’t press any key.

Syntax: input(message)

Here, the message inside the parenthesis refers to the text that programmers intend to show to the user.

Example 1: The following code illustrates the usage of command input() is in python. Here, the two integers are being taken as input.

# Python program to understand the use of input() command
val1 = input("Enter the 1st value: ")
print(val1)
val2 = input("Enter the 2nd value: ")
print(val2)

Output:

Commands in Python

Example 2: The following program shows how to check the type of inputted value. Here, integer and string are considered.

# Program to check the type of inputted value in Python


x = input ("Enter any number :")
print(x)
s = input("Enter any name : ")
print(s)


# Printing type of input value
print ("type of number", type(x))
print ("type of name", type(s))

Output:

Commands in Python

5. len command

To fetch the total number of items present in an object, length() or len() commands are used.

It returns the total no. of characters present if the input object is a string.

It returns the total no. of elements present if the input object is a list or a tuple.

It returns an error if the input object is an integer.

Syntax: len(object)

Here, the object inside parenthesis refers to the target object whose length is to be found.

Example: This example shows the usage of the len command. Here, three objects String, tuple and list are being considered.

# Python program to illustrate the use of the len() method


# with string 
str = "javatpoint"
print(len(str))


# with tuple
tpl = (12,72,39)
print(len(tpl))


# with list
lst = [11,27,32,45]
print(len(lst))

Output:

Commands in Python

6. Range command

To create an order of integers that starts from 0 (start value is 0 by default) and ends before n.

Here n is not included in the created numbers.

This command is mostly employed in the case of loops.

Syntax: range (start value, stop value, step value) 

Here,

The start value marks the starting of the range, it is 0 by default.

Stop value marks that no. before which user wants to terminate the loop.

The step value marks the count of increments in the given range.

Example:


# Python Program to understand range () command


# the numbers less than 20 are getting printed
for i in range (20):
	print (i, end=" ")
print ()


#Here, the range command is being used for iteration
lst = [10, 20, 30, 40]
for i in range (len (lst)):
	print (lst[i], end=" ")
print ()


# sum of first 20 natural number is being performed
sm = 0
for i in range (1, 21):
	sm = sm + i
print("The Sum of first 20 natural number :", sm)

Output:

Commands in Python

7.Round command

To round a number to specified correctness in decimal digits, the round command is taken into account. That means the round command can be used to round off the no. when there are so many digits after decimal in a float point number. Here, one can mention the no. of digits after the decimal point that is to be kept.

Syntax: round (number, digits) 

Here,

The number refers to the no. that has to be rounded off.

Digits refer to the no. of digits that has to be kept after the decimal point.

Example 1: When only 1 argument is present. In the case of int, no rounding off but in the case of float, values get rounded off to the nearest number. If the value is close is less than 5, it gets rounded off to that no. only but if the value is greater than and equal to 5, it gets rounded off to the succeeding number.

# The program to understand round command in python when one argument is present


# for integer datatype
print (round (156))
print (round (16))
print (round (46))


# for float point datatype
print (round (86.6))
print (round (51.5))
print (round (51.4))

Output:

Commands in Python

Example 2: When both the arguments are present, the value gets rounded off as per the no. of digits specified in the 2nd argument.

#program to understand round command in python 


# when the last second digit is =5
print (round (3.6715, 3))


# when the last second digit is >=5
print (round (4.6726, 2))


# when the last second digit is <5
print (round (8.63973, 4))

Output:

Commands in Python

8.Loop command

While and for are two primitive loop commands used in python language.

Here, we will try to understand the working of both of them.

while loop

It is a looping command that gets executed as long as the condition is true.

Syntax:

Condition of while:
statements
update iterator

Example 1: The code here illustrates the working of the while loop

# Python program to understand while loop
Counter=0
While (counter < 10):
            Counter= counter + 1
Print(“JavaTpoint)

Output:

Commands in Python

Example 2: The code shows the working of the while loop

# Python program to understand a single statement while block
counter = 0
while (counter < 5): counter += 1; print("Bonjour World")

Output:

Commands in Python

For loop

It is a looping statement that is used to execute a statement for the given no. of times as long as the condition is true.

Syntax:

for x in sequence:

statements

Example 1: Now, let us see the code to understand the code better.

#python program to understand the working of for loop


hillstation = ["Nainital", "Darjeeling", "gangtok", "Manali"]
for x in hillstation:
  print (x)

Output:

Commands in Python

Example 2: Now, let us understand the code to understand the code better

# A python program to illustrate the for loop which use a break statement 


Hillstations = ["Nainital", "Darjeeling", "Gangtok", "Ooty", "Manali"]
for x in Hillstations:
  print (x)
  if x == "Ooty":
    break

Output:

Here, the hill stations till Ooty gets printed as the loop encounters a break statement after that.

Commands in Python

Let us now learn some string commands used in python.

  • isalnum()– To check if all the characters of a given string are either alphabets or numbers, the isalnum command is used. (alphabet and numbers are together called alphanumeric characters)

It returns a Boolean value after checking all the characters of the string.

Syntax: stringname.isalnum()

Example:

# Python program to illustrate the usage of isalnum command
# string contains either alphabet or number
Val1 = “Newyear2023”


Print(val1.isalnum())


# string contains whitespace
Val2 = “New Year 2023”


print(val2.isalnum()

Output:

val1 contains the alphabet as well as numbers so the output is true.

val2 contains the white space character along with alphabet and number so the output is false. 

Commands in Python
  •  capitalize() -  Toconvert the first character of the string to uppercase if it is written in lowercase, the capitalize command is taken into account. It will leave the string as it is if the first character of the string is uppercase or an integer or any special character.

Syntax: stringname.capitalize()

Example:

# Python program to illustrate the usage of capitalize command 


string = "JAVATPOINT is very useful website"


# it converts the first character of the string into uppercase and others to lowercase


capitalized_string = string.capitalize()


print (capitalized_string )

Output:

The first character of the string here is J which remains as it is while the other characters get converted into a lower case.

Commands in Python
  • find() -To search for a substring present in a string, the find() command is taken into account.  It returns the index of the foremost occurrence of the substring if it is present else it returns -1. 

Syntax: string.find(substring)

Here,

Substring marks that part of a string that is to be found in a larger string

Example:

#python program to illustrate the find command


message = 'programming is really interesting as it enhances the thinking ability’


# checking the index of 'it'
Print (message.find('it'))


# checking the index of 'thinking'
Print (message.find ('thinking'))

Output:

The code is written to understand the use of the find command.

The word which is to be found and its index is given as output. 

Here, the index of ‘it’ is 36 which is shown in the output, and the index of the word ‘thinking’ is 52 which is given as output.

Commands in Python
  • center() -To line up a string in the center, using a stated character (which is by default a space) as the fill character.

Syntax: string.center (length, character)

Here,

Length marks the maximum length of the string

Character marks the character that is to be inserted

Example:

#python program to illustrate center command


string = "India is a great country"


# returns the centered padded string of length 24 
string1 = string.center(50, '*')


print(string1)

Output:

The code illustrates the usage of the center command. Through this command, asterisks get inserted at the left end as well as at the right end keeping our string in the center.

Commands in Python

s

  • count() - To return the sum of occurrences of a substring in a string object, the count function is taken into account.

Syntax: stringname.count (substring, start index, end index)

Here,

Substring marks the string which we want to search in the main string.

The start index marks the starting index of the substring which we want to search.

The end index marks the last index of the substring which we want to search.

Example 1: When start and end indexes are not provided.

#python program to understand the usage of count command


string = 'javaTpoint is a popular website among engineers'


# number of occurrences of character 'i'


print('Number of occurrence of character i:', string.count('p'))


# number of occurrences of character 'a'


print('Number of occurrence of character a:', string.count('a'))

Output:

The code here illustrates the usage of the count command. Here, the no. of occurrence of characters p and a are being calculated. Here, its occurrence is being checked in the whole string rather than the part of the string.

Commands in Python

Example 2: When substring, start and end indexes are present.

# defining the string
string = "java is a good language, isn't it?"
substring = "o"


# counting after first 'o' and before the last 'o'
count = string.count(substring, 5, 45)


# printing the count of occurrence of o
print("The count of character o is:", count)

Output:

In this code, the usage of command count is illustrated when starting as well as ending indexes are provided.

Commands in Python

List commands in python

Let us see some of the list commands used in python.

1. append()

To add an element at the end of a list, the append command is taken into account.

Syntax: list.append (element)

The list marks the list object in which one wants to add an element.

An element marks the new item that one wants to add to the list.

Example:

tourist_place = ['Darjeeling', 'ooty', 'Nainital', 'Silliguri']
print(tourist_place)
tourist_place.append("Shimla")
print(tourist_place)

Output: In this example, the element Shimla is being added to the list named tourist_place

Commands in Python

2. copy()

To create a new copy of the list object, the copy command is taken into account. A new list object is returned.

Syntax: list.copy()

Example –

#python program to illustrate the copy command
 
tourist_place = ['Darjeeling', 'ooty', 'Nainital', 'Silliguri']
print(tourist_place)
x = tourist_place.copy()
print(x)


Output –

In this example, the content of one list named tourist_place is being copied to another list named x.

Commands in Python

3. insert()

To add an element at a specified position in the list object, the insert command is taken into account. It takes two parameters position and an element. 

Syntax: list_name.insert(location, element)

Example –


# creating a list of odd numbers
odd_numbers = [21, 33, 75, 57, 25, 43]
print('Old List:', odd_numbers)


# inserting 41 at index 5
odd_numbers.insert(5, 41)
print('New List:', odd_numbers)		


Output –

In this example, a new element is inserted in the list named odd_numbers with the aid of the insert command.

Commands in Python

location refers to the position where one wants to insert a new element. The element will always get inserted at the end when one gives a position greater than the number of elements in the list.

element refers to the new element that needs to be added to the list.

4. pop()

To eliminate an element from a specified location in the list, the pop command is taken into account. The element is returned after removing it from the list.

Syntax: listname.pop(location)

location refers to the position in which one wants to remove the element from the list.

Example-

# Creating a list of odd numbersof odd numbers
odd_numbers = [23, 63, 35, 87, 90, 67, 54]
# Removing the element at index 5
popped_element = odd_numbers.pop(5)
print('Popped Element:', popped_element)
print('List after updatation:', odd_numbers)

Output:

Here, the element presents at index 5 is popped from the list named odd_numbers.

Commands in Python

5.  reverse()

To reverse the order of all elements in the list, the reverse command is taken into account. the original list object is modified but nothing is returned.

Syntax: list.reverse()

#Python program to reverse the strinf
tourist_places = [‘Darjeeling’, ‘Ooty’ ‘Nilgiri’, ‘Rajgir’, ‘Agra’]
tourist_places.reverse()
Print(tourist_places)

Output:

Here, the elements present in a list named tourist_places are reversed using the reverse command.

Commands in Python

To sort the elements of the list in ascending order by default, the sort command is taken into account.

6. sort()

Syntax: list.sort()

Example:

#Python program to illustrate the sort command
tourist_places = [‘Darjeeling’, ‘Ooty’ ‘Nilgiri’, ‘Rajgir’, ‘Agra’]
print(“Before sorting:”)
print(tourist_places)
print(“After sorting:”)
Print(tourist_places)

 Output:

Commands in Python

Tuple commands in python

Now, let us discuss some commands of tuples.

1.. count():

To count the existence of an element in the tuple, the count method is taken into account.

Syntax: tuple.count(element)

An element marks that element that is to be counted.

#python program to understand count command in tuple
# tuple of vowel
vowels = ('a', 'e', 'i', 'o', 'i', 'u', 'o', 'i')
# count of element 'o'
count = vowels.count('o')
# printing the count of 'o'
print('The count of o is:', count)
# count of element 't'
count = vowels.count('t')
# printing the count of 't'
print('The count of t is:', count)

Output:

Here, the occurrence of vowel o is 2 and the occurrence of vowel t is 0

Commands in Python

2. index ()

To find the index of the first occurrence of an element, the index () method is taken into account. It will raise a ValueError if the searched element is not found in the whole tuple.

Syntax: tuple.index(element)

element refers to the item that is to be searched.

Example:

#python program to understand the index command used in tuple
animals = ['cat', 'giraffe', 'goat', 'tiger', 'dog', 'rabbit', 'horse']
tourist_place = ['Darjeeling', 'Agra', 'ooty', 'Nainital', 'Silliguri']
# get the index of 'ooty'
index1 = animals.index('dog')
index2 = tourist_place.index('ooty')
print(index1)
print(index2)

Output:

Here, the dog is present at the 4th position in tuple named animals and the Ooty is present at the 2nd position in a tuple named tourist_places.

Commands in Python



ADVERTISEMENT
ADVERTISEMENT