0

I have a function that takes two parameters (a list and an input number). I have code that breaks the input list into a smaller grouping of lists. I then need to check this new list and make sure all of the smaller lists are at least as long as the input number. However when I try to iterate over the sublists within my main list, for some reason certain sublists are excluded (in my example it is the sublist located at mainlist[1]. Any idea why this is happening???

def some_function(list, input_number)
    ...
    ### Here I have other code that further breaks down a given list into groupings of sublists
    ### After all of this code is finished, it gives me my main_list
    ...

    print main_list
    > [[12, 13], [14, 15, 16, 17, 18, 19], [25, 26, 27, 28, 29, 30, 31], [39, 40, 41, 42, 43, 44, 45]]

    print "Main List 0: %s" % main_list[0]
    > [12, 13]

    print "Main List 1: %s" % main_list[1]
    > [14, 15, 16, 17, 18, 19]

    print "Main List 2: %s" % main_list[2]
    > [25, 26, 27, 28, 29, 30, 31]

    print "Main List 3: %s" % main_list[3]
    > [39, 40, 41, 42, 43, 44, 45]

    for sublist in main_list:
        print "sublist: %s, Length sublist: %s, input number: %s" % (sublist, len(sublist), input_number)
        print "index of sublist: %s" % main_list.index(sublist)
        print "The length of the sublist is less than the input number: %s" % (len(sublist) < input_number)
        if len(sublist) < input_number:
            main_list.remove(sublist)
    print "Final List >>>>"
    print main_list

> sublist: [12, 13], Length sublist: 2, input number: 7
> index of sublist: 0
> The length of the sublist is less than the input number: True

> sublist: [25, 26, 27, 28, 29, 30, 31], Length sublist: 7, input number: 7
> index of sublist: 1
> The length of the sublist is less than the input number: False

> sublist: [39, 40, 41, 42, 43, 44, 45], Length sublist: 7, input number: 7
> index of sublist: 2
> The length of the sublist is less than the input number: False

> Final List >>>>
> [[14, 15, 16, 17, 18, 19], [25, 26, 27, 28, 29, 30, 31], [39, 40, 41, 42, 43, 44, 45]]

Why is my sublist located at mainlist[1] being completely skipped??? Thanks for any help in advance.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
GetItDone
  • 566
  • 7
  • 22

2 Answers2

1

An 'if' in a list comprehension would work:

>>> x =  [[12, 13], [14, 15, 16, 17, 18, 19], [25, 26, 27, 28, 29, 30, 31], [39, 40, 41, 42, 43, 44, 45]]
>>> [y for y in x if len(y)>=7]
[[25, 26, 27, 28, 29, 30, 31], [39, 40, 41, 42, 43, 44, 45]]
Francis Potter
  • 1,629
  • 1
  • 17
  • 19
0

It looks like you're changing the list as you iterate over it. This is not allowed and can lead to undefined behavior.

See this answer.

Community
  • 1
  • 1
Codie CodeMonkey
  • 7,669
  • 2
  • 29
  • 45