python array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

21st Jan 2023, 10:20 AM
Sami Yemane
Sami Yemane - avatar
5 Answers
+ 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)
21st Jan 2023, 6:00 PM
Tibor Santa
Tibor Santa - avatar
+ 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
21st Jan 2023, 11:16 AM
JuZip
+ 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.
22nd Jan 2023, 12:13 AM
Bob_Li
Bob_Li - avatar
0
I don't think I understood your question/problem. Can you rephrase?
21st Jan 2023, 10:23 AM
Lamron
Lamron - avatar
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
21st Jan 2023, 11:17 AM
Bob_Li
Bob_Li - avatar