0
python array
in a = ["3", "4","5","6"] what i want to do is when i am looping through this array and lets say i have reached the 2 item which would be 4 i want 3 to be treated as thou it is the last item
5 Respostas
+ 4
It seems to me you want to stop the iteration in a loop. You can do this with the break statement.
nums = list(range(9))
for n in nums:
# check if you need to stop
if n == 4:
break
# otherwise do something
print(n)
+ 1
Hey Sami Yemane, can you post your code what you tried so far?
Some hints:
- in python the element counting stars with 0 so the index of the second element will be 1
-your values are stored as string type but seem to be integer. If so you need to test against a string not integer.
- if you want the index before the chosen you can retrieve the index i of your element and enter it's antecedent with i-1
+ 1
Tibor Santa
you're right, i thought he meant the "3" in in the first item becomes the last item, so maybe he was talking about cyclic lists...
if so, another method is list slicing.
a = ["3","4","5","6"]
for n in a[:3]:
print(n)
will print
3
4
5
making it behave as if the 3rd item is the last item.
0
I don't think I understood your question/problem. Can you rephrase?
0
maybe you want circular or cyclic list.
it does not end.
but you have to use next() because index becomes meaningless. and unless you know what was called before, it's hard to know what value comes when you call next()
https://code.sololearn.com/cmGXl1fG90gl/?ref=app