I am using Python2.7 and I would like to loop through a list x times.
a=['string1','string2','string3','string4','string5']
for item in a:
print item
The above code will print all five items in the list, What if I just want to print the first 3 items? I searched over the internet but couldn’t find an answer, it seems that xrange() will do the trick, but I can’t figure out how.
Thanks for your help!
Sequence Slicing is what you are looking for. In this case, you need to slice the sequence to the first three elements to get them printed.
Even, you don’t need to loop over the sequence, just join it with a newline and print it