sam
sam

Reputation: 19194

iterating to nth value in python

How I will iterate for loop in python for 1 to specific value?

I can iterate on list in python like :

for x in l:
    print x

But.
If i wanted to iterate from 1 to number th, in matlab I will do :

str = "abcd"  
for i=1:z
    for j=1:y
        if  s(:,i)==s(j,:)'
            Seq(i)=str(j);
        end
    end
end

How I will iterate such in python?

Upvotes: 1

Views: 88

Answers (4)

falsetru
falsetru

Reputation: 369334

Use slice notation (This creates temporary list that contains first n items):

>>> s = "abcd"
>>> for x in s[:2]:
...     print(x)
...
a
b

or use itertools.islice:

>>> import itertools
>>> for x in itertools.islice(s, 2):
...     print(x)
...
a
b

Upvotes: 1

alvas
alvas

Reputation: 122168

You need to get use to the idea of slicing in python, see Explain Python's slice notation

Non-slicing:

a = [1,2,3,4,5,6,7,8]
n = 5

for i in range(n):
  print a[i]

With slices:

a = [1,2,3,4,5,6,7,8]
n = 5

print a[:n]

Upvotes: 1

Kobi K
Kobi K

Reputation: 7931

To access values in lists, use the square brackets for slicing along with the index.

for x in l[start:end]:
        print x

You have a grate post here about slice notation

Another grate link about lists

Example 1:

myList = [1, 2, 3, 4]

for x in myList[:-1]:
    print x

Output:

1
2
3

Example 2:

myList = [1, 2, 3, 4]

for x in myList[1:3]:
    print x

Output:

2
3

Upvotes: 1

Arjen Dijkstra
Arjen Dijkstra

Reputation: 1549

for i in range(0, 11):
    print i

HTH

Upvotes: 3

Related Questions