-4

I know there is quite a number of similar questions on stackoverflow but they don't seem to be solving my problem. If you look at my code below, you can see that I am creating a temp list of ads called "tempAdList" and when the if condition evaluate true I am creating a list of lists called "ad_list". I am appending to "ad_list" so I am expecting that everytime the "if statement" evaluates true a new list of 4 ads is appended to "ad_list" but for whatever reason I am getting below output which is not what i am looking for. what am I doing wrong here?

ads = Advert.objects.all()

counter = 1
tempAdList = []
ad_list = []

for i, ad in enumerate(ads):
    tempAdList.append(ad)
    if counter == 4:
        # print(tempAdList)
        ad_list.append(tempAdList)
        print(ad_list)
        tempAdList.clear()
        counter = 0
    counter += 1

    adsNum = len(ads)
    # print("i = {} and adsNum = {}".format(i, adsNum))
    if i == adsNum -1 and adsNum % 4 != 0:
        ad_list.append(tempAdList)

output:enter image description here

Ayanda Khanyile
  • 235
  • 2
  • 14

3 Answers3

0

If you just want a list of lists, where inner lists are having 4 elements. You can try something like :

new_list = [ads[i:i+4] for i in range(0, len(ads), 4)] 
soumya-kole
  • 1,111
  • 7
  • 18
0

Using the clear-method on a list also affects all references to it, e.g.

>>a = [1, 2, 3]
>>b = a
>>a.clear()
>>print('a =',a)
a = []
>>print('b =',b)
b = []

So what you are doing in ad_list.append(tempAdList) is to repeatedly add references to the same object to ad_list, i.e. each time you update tempAdList, the same update is done for each of those references. What you really want to do is reset tempAdList with a new object, so replace tempAdList.clear() with tempAdList=[].

Alperino
  • 486
  • 3
  • 10
0

Every time you do tempAdlist.clear(), you cleared all elements of the list. But because you appended the list to ad_list, you basically cleared it there too. so you have one less list. This is because of the nature of lists being referenced instead of recreated. What you want is to create a list from tempAdlist when appending, like so: ad_list.append(list(tempAdlist)) this way it will be a whole new list from the tempAdlist. Essentially your code becomes:

ads = Advert.objects.all()

counter = 1
tempAdList = []
ad_list = []

for i, ad in enumerate(ads):
    tempAdList.append(ad)
    if counter == 4:
        # print(tempAdList)
        ad_list.append(list(tempAdList))
        print(ad_list)
        tempAdList.clear()
        counter = 0
    counter += 1

    adsNum = len(ads)
    # print("i = {} and adsNum = {}".format(i, adsNum))
    if i == adsNum -1 and adsNum % 4 != 0:
        ad_list.append(list(tempAdList))
pintert3
  • 67
  • 1
  • 8