Python List Index Method-python exercises for beginners |My programming school


Python List Index Method Flowchart for List element

Python List Index Method-python exercises for beginners | My programming school

From this tutorial, you may be studying about Python checklist Index technique. You will see how you can apply it to sequences with the assistance of examples.

Note: The syntax used in the beneath part is for Python 3. You can change it to every other variations of Python.

Python List Index

To Learn about Lists – Read Python List

List Index Method

The Index operate is a built-in checklist technique that permits you to find out the index or place of a component in a sequence.

In different phrases, this technique searches for a component in the checklist and returns its index.

Its syntax is as follows:

List_name.index(<factor>)

It takes the factor as an argument and returns the index. Please notice that you could present any enter such as an inventory or a tuple or a substring.

See the beneath instance.

>>> myList = ['1', '11', 1, 'a', 'x', 1.1]
>>> myList.index(1)
2
>>> myList.index('x')
4

How does the Index() operate work?

It takes one enter which is the factor for which you need the index or place as the output.

This technique searches for the factor in the checklist and returns the index matches its worth else raises the ValueError error.

While looking for substrings, it raises the next error.

"Substring not found"
>>> first = 'Python is the language of the long run.'
>>> print(first.index('lang', 10))
14
>>> print(first.index('invalid', 10))
Traceback (most up-to-date name last):
File "<pyshell#34>", line 1, in <module>
print(first.index('invalid', 10))
ValueError: substring not discovered
>>>

The flowcharts beneath try to clarify it in a diagram:

For components in the checklist:

Python List Index Method Flowchart for List element

For characters in the string:

Python List Index Method Flowchart for Substring

Program Examples

Using the improper factor

myList = [2,3,4,5,6]

myList.index(1)

The output is:

Traceback (most up-to-date name last):
File "C:PythonPython35test.py", line 3, in <module>
myList.index(1)
ValueError: 1 is not in checklist

Find the factor index in a tuple

myList = [2,3,(3,4),5]

print(myList.index((3,4)))

The outcome is:

2

Python List Index Method-python exercises for beginners -My programming school

For more Search in Wikipedia

Categories

You have successfully subscribed to myprogrammingschool

There was an error while trying to send your request. Please try again.

My Programming School will use the information you provide on this form to be in touch with you and to provide updates and marketing.