Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (Retired) Shopping List Lists

How I know where is anything in a list?

Ex.:

>>> my_list = list('Hello')                 
>>> 'H' in my_list                          
True                                        

# I know that "H" is in the list, but if want to know where is 'H' in the list, How I do it?

[MOD: added ```python formatting -cf]

3 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points
# For a list you can use 'index'. It throws error if item not found

>>> my_list = list('Hello')                 
>>> 'H' in my_list  
True
>>> my_list.index('H')
0
>>> my_list.index('l')
2
>>> my_list.index('z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'z' is not in list

# Strings can act like lists
>>> my_string = 'Hello'
>>> 'H' in my_string
True
# find returns index, or '-1' if not found
>>> my_string.find('l')
2
>>> my_string.find('z')
-1

# Can also use 'index()'. It throws error if item not found
>>> my_string.index('o')
4
>>> my_string.index('z')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

# can use 'index' on string but throws an error if target not found

More info on str.find(), more info on index() under list type

Excelente!! Thank you

Good answer man