22
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
  • 238,746
  • 336
  • 750
  • 1,061

4 Answers4

88

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
  • 16,569
  • 8
  • 83
  • 100
27
for index, s in enumerate(stocks_list):
    print index, s
nosklo
  • 205,639
  • 55
  • 286
  • 290
3
[x for x in range(len(stocks_list)) if stocks_list[x]=='MSFT']
user1713952
  • 167
  • 3
  • 9
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