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!
To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
Repeat N Times in Python Using the range() Function The most common way to repeat a specific task or operation N times is by using the for loop in programming. We can iterate the code lines N times using the for loop with the range() function in Python.
In your example, the second x is the variable used by the for loop, and the first x is simply an expression, which happens in your case to be just x . The expression can be whatever you like, and does not need to be in terms of x .
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.
a=['string1','string2','string3','string4','string5']
for item in a[:3]:
print item
Even, you don't need to loop over the sequence, just join it with a newline and print it
print '\n'.join(a[:3])
I think this would be considered pythonic:
for item in a[:3]:
print item
Edit: since a matter of seconds made this answer redundant, I will try to provide some background information:
Array slicing allows for quick selection in sequences like Lists of Strings. A subsequence of a one-dimensional sequence can be specified by the indices of left and right endpoints:
>>> [1,2,3,4,5][:3] # every item with an index position < 3
[1, 2, 3]
>>> [1,2,3,4,5][3:] # every item with an index position >= 3
[4, 5]
>>> [1,2,3,4,5][2:3] # every item with an index position within the interval [2,3)
[3]
Note that the left endpoint is included, the right one is not. You can add a third argument to select only every n
th element of a sequence:
>>> [1,2,3,4,5][::2] # select every second item from list
[1, 3, 5]
>>> [1,2,3,4,5][::-1] # select every single item in reverse order
[5,4,3,2,1]
>>> [1,2,3,4,5][1:4:2] # every second item from subsequence [1,4) = [2,3,4]
[2, 4]
By converting lists to numpy arrays, it is even possible to perform multi-dimensional slicing:
>>> numpy.array([[1,2,3,4,5], [1,2,3,4,5]])[:, ::2]
array([[1, 3, 5],
[1, 3, 5]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With