2

I am trying to find an element in a list (string) and then print the index. Here is my code:

def checkLen():
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
position = 0
for i in days:
    if i == "Monday":
        position = i
        print("Found it")
        print(position)

But i am getting the result:

Found it
Monday

I have discovered that ,unlike other programming language that i know, Python variable type can change, which is why the Number type "position" changes to a "str", how do i save the index in position?

2
  • 1
    To use your code, you need to increment position within the loop. Commented Jul 8, 2014 at 10:06
  • One more way you can do this would be for i, day in enumerate(days): Commented Jul 8, 2014 at 13:44

4 Answers 4

3

Lists have an index method that you can use

def checkLen(): 
     days = ["Monday", "Tuesday", "Wednesday", "Thursday" "Friday", "Saturday", "Sunday"]
     try:
         position = days.index("Monday")
         print("Found it") 
     except ValueError:
         position = None # or 0 if you want
         print("Not present") 
     print(position)
Sign up to request clarification or add additional context in comments.

3 Comments

this will produce error if the monday not present in list
@OjonugwaOchalifu how you use else here.can you explain
:D I was still referring to my original code.You sir,are correct.
3

Use enumerate. It returns both the position and the item:

def checkLen():
    days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    for position, day in enumerate(days):
        if day == "Monday":
            print("Found it")
            print(position)

Comments

1
 def checkLen():
    days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    if "Monday" in days:
        print "found"
        print days.index("Monday")

you dont need to loop the days . just use in if it is found then index

Comments

1

there is an index function for lists:

days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
print(days.index("Monday"))

note that this will raise an exception if the item is not in the list but will execute faster than looping over the list, especially if you have long lists.

however it will only give you the first index, so if there are duplicates you'll have to use other methods to find them.

a good resource for reading is http://effbot.org/zone/python-list.htm

as pointed out by Frerich Raabe in python most people tend to write code to assume that what you are looking for is there (ie the list has the element you are trying to find) and catch the exception raised if its not (exception raised is ValueError)

try not to use a general exception when you know the specific exception that should be raised as with more complex code it can make it harder to find other problems where another function call fails.

1 Comment

I'd +1 this if you'd extend your answer to point out that in Python, people commonly "ask for forgiveness, not permission", i.e. you'd rather try to get the index and catch any error than to first check whether the element is contained.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.