24
for s in stocks_list:
    print s

how do I know what "position" s is in? So that I can do stocks_list[4] in the future?

TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

4 Answers4

90

If you know what you're looking for ahead of time you can use the index method:

>>> stocks_list = ['AAPL', 'MSFT', 'GOOG']
>>> stocks_list.index('MSFT')
1
>>> stocks_list.index('GOOG')
2
Ben Dowling
  • 17,187
  • 8
  • 87
  • 103
28
for index, s in enumerate(stocks_list):
    print index, s
nosklo
  • 217,122
  • 57
  • 293
  • 297
3
[x for x in range(len(stocks_list)) if stocks_list[x]=='MSFT']
malekcellier
  • 177
  • 3
  • 10
0

The position is called by stocks_list.index(s), for example:

for s in stocks_list:
    print(stocks_list.index(s))
B Shmid
  • 1
  • 2
  • 2
    This is already stated by [the top-voted answer](https://stackoverflow.com/a/7532611/3025856). When answering questions with existing answers, be sure to review those answers, and only add a new answer if you have a different solution, or a substantially improved explanation. Later, when you have a bit more reputation, you'll also be able to upvote existing answers in order to validate their guidance. – Jeremy Caney Nov 03 '21 at 00:15
  • No it wasn't. That answer only said "If you know what you're looking for ahead of time" while mine does not necessitate that. – B Shmid Nov 03 '21 at 10:10