Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Find Index of Element in Array - Python
Next article icon

Difference Between find() and index() in Python

Last Updated : 21 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Both methods are used to locate the position of a substring within a string but the major difference between find() and index() methods in Python is how they handle cases when the substring is not found. The find() method returns -1 in such cases, while index() method raises a ValueError.

Example of find()

Python
s = "hello world"  # Finds the position of the substring "world" print(s.find("world"))  # Returns -1 when substring is not found print(s.find("python"))  # Finds the position of "o" starting from index 5 print(s.find("o", 5)) 

Output
6 -1 7 

Explanation:

  • s.find("world") returns 6 because the substring "world" starts at index 6.
  • s.find("python") returns -1 as substring "python" is not present in string.
  • s.find("o", 5) starts the search from index 5 and finds the first occurrence of "o" at index 7.

Example of index()

Python
s = "hello world"  # Finds position of the substring "world" print(s.index("world"))  # Raises a ValueError when substring is not found print(s.index("python"))  # Finds position of "o" starting from index 5 print(s.index("o", 5)) 
6  ERROR! Traceback (most recent call last):   File "<main.py>", line 7, in <module> ValueError: substring not found

Explanation:

  • s.index("world") returns 6 because substring "world" starts at index 6.
  • When s.index("python") is executed then it raises a ValueError as the substring "python" is not in string.
  • s.index("o", 5) starts searching from index 5 and finds the first occurrence of "o" at index 7.

When to use find() and index()?

  • Use find() when we need to check if a substring exists and do not want to handle exceptions.
  • Use index() when we are sure that the substring exists or we want an exception to be raised if it doesn't exist.

Next Article
Find Index of Element in Array - Python
author
vijayakumarchinthala
Improve
Article Tags :
  • Strings
  • Python
  • Python Programs
  • DSA
  • python-string
  • Python-string-functions
Practice Tags :
  • python
  • Strings

Similar Reads

  • Difference Between Enumerate and Iterate in Python
    In Python, iterating through elements in a sequence is a common task. Two commonly used methods for this purpose are enumerate and iteration using a loop. While both methods allow us to traverse through a sequence, they differ in their implementation and use cases. Difference Between Enumerate And I
    3 min read
  • Find Index of Element in Array - Python
    In Python, arrays are used to store multiple values in a single variable, similar to lists but they offer a more compact and efficient way to store data when we need to handle homogeneous data types . While lists are flexible, arrays are ideal when we want better memory efficiency or need to perform
    2 min read
  • Find index of element in array in python
    We often need to find the position or index of an element in an array (or list). We can use an index() method or a simple for loop to accomplish this task. index() method is the simplest way to find the index of an element in an array. It returns the index of the first occurrence of the element we a
    2 min read
  • Difference between List VS Set VS Tuple in Python
    In Python, Lists, Sets and Tuples store collections but differ in behavior. Lists are ordered, mutable and allow duplicates, suitable for dynamic data. Sets are unordered, mutable and unique, while Tuples are ordered, immutable and allow duplicates, ideal for fixed data. List in PythonA List is a co
    3 min read
  • Python - Difference between Uni length slicing and Access Notation
    There are various ways to extract elements, Uni length slicing and Access Notations are among them. Let's check difference between them. Difference #1 : Different behaviour with Different Containers The access notation return element in both List and Strings, but return 1 length strings while slicin
    3 min read
  • Handling " No Element Found in Index() " - Python
    The task of handling the case where no element is found in the index() in Python involves safely managing situations where the desired element does not exist in a list. For example, with the list a = [6, 4, 8, 9, 10] and the element 11, we want to ensure the program doesn't raise an error if the ele
    3 min read
  • Python - Find Index containing String in List
    In this article, we will explore how to find the index of a string in a list in Python. It involves identifying the position where a specific string appears within the list. Using index()index() method in Python is used to find the position of a specific string in a list. It returns the index of the
    3 min read
  • Python - Get Even indexed elements in Tuple
    Sometimes, while working with Python data, one can have a problem in which we need to perform the task of extracting just even indexed elements in tuples. This kind of problem is quite common and can have possible application in many domains such as day-day programming. Let's discuss certain ways in
    5 min read
  • Find element in Array - Python
    Finding an item in an array in Python can be done using several different methods depending on the situation. Here are a few of the most common ways to find an item in a Python array. Using the in Operatorin operator is one of the most straightforward ways to check if an item exists in an array. It
    3 min read
  • Python - Distance between occurrences
    Sometimes, while working with Python Strings, we can have a task in which we need to find the indices difference between occurrences of a particular character. This can have applications in domains such as day-day programming. Let us discuss certain ways in which this task can be done. Method #1: Us
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences