Stas Poritskiy
Stas Poritskiy

Reputation: 19

why do i get NONE in list?

Consider this LIST:

test = ["stas", "doug", "saman", "movie"]
for q in range(len(test)):
    PreGroup = None
    if (q > 0):
        PreGroup = test[q-1]
    print PreGroup

How can i get rid of NONE? as the FIRST output? i need to have the q-1 set there, or at least i think, because i need to have PreGroup to be one Index BEFORE the current.

my PreGroup must not have None, since i am passing it later in my code, and if it gets NONE, i get an error.

Thanks.

Upvotes: 0

Views: 118

Answers (4)

Rörd
Rörd

Reputation: 6681

You're not expressing very clearly what it is that you want, but I suppose what you're saying is that you want both a valid current group test[q] and a valid previous group test[q-1] during every iteration of the loop. In that case, you could use range(1, len(test)) to make q start at 1 rather than 0.

Alternatively, you could do this without using any index with this loop:

for (pre_group, group) in zip(test, test[1:]):
    print pre_group, group

Upvotes: 1

sepp2k
sepp2k

Reputation: 370112

You don't want to set PreGroup (to something other than None) if q is 0. That's fine, but then you print the value of PreGroup whether it has been set or not. If you put the print inside the if as well, it will only print if PreGroup has been set to test[q-1]. You can then also remove the PreGroup = None line because PreGroup doesn't need to exist outside of the if.

An even better way to solve your problem though, would be to simply let the loop start at 1 instead of 0. That way you don't have to even check whether q is 0. You can do that by using range(1, len(test)).

Upvotes: 1

Argiri Kotsaris
Argiri Kotsaris

Reputation: 492

Maybe something like this

test = ["stas", "doug", "saman", "movie"]
for q in test:
    PreGroup = None
    q = test.index(q)
    if q > 0:
        PreGroup = test[q]
    print PreGroup

Upvotes: -2

Ethan Furman
Ethan Furman

Reputation: 69031

range starts at 0, so the first time through the test if (q > 0) fails, and PreGroup stays at None.

As a side note, you don't need parenthesis around the if test.

Upvotes: 1

Related Questions