Reputation: 111
I have this code:
U = [1,2,3,4,5,6,7,8,9,10,11,12]
def bla(anzahl):
zaehlwerk = 0
while zaehlwerk < anzahl:
for x in U:
zaehlwerk = zaehlwerk +1
print x
my query:
bla(3)
I hoped that now I would get the first 3 list items, but instead I get the whole list.
1
2
3
4
5
6
7
8
9
10
11
12
I tried to debug because I thought that maybe the counter wouldn't work, but it does. But then where is my error?
Upvotes: 0
Views: 5085
Reputation: 19743
use slicing :
>>> U = [1,2,3,4,5,6,7,8,9,10,11,12]
>>> U[:3]
[1, 2, 3]
U[stat-index:end-index]
, you will get element from start-index to one less end-index, as in above example
>>>U[2:6]
[3, 4, 5, 6]
what you need to do is this using slicing:
def print_list(n):
print "\n".join(map(str,U[:n]))
print_list(3)
output:
1
2
3
Upvotes: 6
Reputation: 1972
for x in U:
is the innermost loop. That is making sure you iterate over everything.
As is you can modify your code to look like
def bla(anzahl):
zaehlwerk = 0
while zaehlwerk < anzahl:
x = U[zaehlwerk]
zaehlwerk = zaehlwerk +1
print x
And that will work for what you want. But more concise would be to to use something like
for index in range(len(anzahl)):
print U[index]
Upvotes: 0