How do I navigate through a Python list for each function call?

Asked

Viewed 255 times

-2

I have this code as an example:

#         0   1   2   3   4
lista = ['1','2','3','4','5']

def nexxt():
    for item in range(len(lista)):
        item += 1       
        print(lista[item])

def back():
    for item in range(len(lista)):
        item -= 1
        print(lista[item])

I want to print every object on every call... Like I call Nexxt he prints 1 because 0 is gone, I call again and he prints 2 and so it goes...and with the back the opposite...I want to adapt this to a project where I can jump and return songs where the list will have the name of each . mp3 and the pygame/ mixer does the rest

This code is not useful, because it does not return correctly from 0 to 4...if someone can give me a light

  • Why do this if you can use a variable as an index.

  • What exactly do you want to do? You just want to print the list elements, or you want to print the contents?

  • I want to print every object on every call... Like I call nexx he prints 1 because 0 is gone, I call again and he prints 2 and so it goes...and with the back the opposite... mp3 and the pygame/ mixer does the rest

1 answer

0


There are many ways to do what you want and one of them is by creating an auxiliary variable to know the current index of the list, working as a pointer that marks where you left off in the list.

Within its functions nexxt and back there should be no loop for since you don’t want to go through your list every call. What you need to do is just increment or decrease the value of the auxiliary variable so that the pointer is changed at each call.

See the example below:

songs = ["Run Away (Moldova).mp3", "Real Gone.mp3", "Sun shine it.mp3", "MADKID - Rise.mp3"]
pointer = 0

def play_song():
    global pointer
    print("Playing " + songs[pointer])

def next_song():
    global pointer
    if pointer < len(songs) - 1: pointer += 1

def back_song():
    global pointer
    if pointer > 0: pointer -= 1
  • Really saved me ksksks, if you need anything just call...

  • Glad it helped. You can upvote if the answer was helpful and accept it if it has answered your question.

  • Psé kkkk, if I may say how...I’m new here and find it difficult to use, I don’t even know how to close the question.

  • Ta seeing those little arrows on the left side of the answer ? Up is upvote (liked) and down is downvote (disliked). Below these arrows is a button that is to accept the answer that when clicking turns green.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.