# Title: Looping through elements in Python # In Python 2, there are 2 ways to loops through a list. # The first method loops through all elements and does not store the position of the element some_unknown_seqeunce = 'BACKTOTHEFUTURE' #using the list we created above, we can print out every letter (without knowing its position!!!) print '--- Method 1 --' for letter in some_unknown_seqeunce: print letter # if we want to access the index or position of the letters we have to use a trick print "--- Method 2 ---" for position in range(len(some_unknown_seqeunce)): print position, ' - ', some_unknown_seqeunce[position] # Sometimes you want to quickly print a list, other times you need the position of elements in the list # Right now we just want to check what letters are in our shortened amino acids list print '--- Comparing Methods ---' short_amino_acids = ['A','C','D','E','F','G','H','I','J','K','L','M'] # print all letters that are amino acids print '--- No index needed ---' for letter in some_unknown_seqeunce: if letter in short_amino_acids: print letter # Many biological sequnces come in pairs, triplets, or larger groups. Check every 3rd amino acid, and print the position. # NOw and idex is needed print '--- Now an index is needed ---' for position in range(len(some_unknown_seqeunce)): if (position % 3 == 0) and (some_unknown_seqeunce[position] in short_amino_acids): # google modulo if you dont understand this print position, ' - ', some_unknown_seqeunce[position]
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question