1

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?

sam
  • 18,509
  • 24
  • 83
  • 116

4 Answers4

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

HTH

Arjen Dijkstra
  • 1,479
  • 16
  • 23
1

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
falsetru
  • 357,413
  • 63
  • 732
  • 636
1

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
Community
  • 1
  • 1
Kobi K
  • 7,743
  • 6
  • 42
  • 86
1

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]
Community
  • 1
  • 1
alvas
  • 115,346
  • 109
  • 446
  • 738