0

I am trying to add data in a list. I used a temp list , swaping its data to another list b and then clearing its data in each iteration When using temp.clear() , my final output is empty.But when using temp = [] i get right output.

Kindly tell why different output is there when using temp.clear() and temp = [].

a=['apple','pizza','veg','chicken','cheese','salad','chips','veg']
b=[]
temp=[]

for i in range(len(a)):
    temp.append(a[i])
    b.append(temp)
    temp.clear()
    #temp = []
print(b)        

Output

#temp.clear()
[[], [], [], [], [], [], [], []]

#temp = []
[['apple'], ['pizza'], ['veg'], ['chicken'], ['cheese'], ['salad'], ['chips'], ['veg']]
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
SKB
  • 771
  • 7
  • 14
  • 3
    " I used a temp list , swaping its data to another list b " that isn't what you are doing. you are appending the same `list` object to the list `b`. since you keep `.clear`ing that same list object, of course you end up with a bunch of references to the same empty list. however, when you do `temp = []`, you create a *new empty list*. – juanpa.arrivillaga Nov 04 '19 at 00:42
  • Possible duplicate of [python list by value not by reference](https://stackoverflow.com/questions/8744113/python-list-by-value-not-by-reference) – Sach Nov 04 '19 at 00:57

1 Answers1

1

temp.clear() removes all items from a list (see docs). temp = [] does not clear any list. Rather it creates a new empty list. Since you append temp to b, these values persist when using temp = [], but are cleared when using temp.clear().

PartialOrder
  • 2,870
  • 3
  • 36
  • 44