0

In some code I was working in, I have two lists l1, l2, and I was planning on extending l1 with l2. There are two obvious ways of doing so

l1 += l2

and

l1.extend(l2)

In my head, I always thought the first was implemented as the second, but after 100 trials on randomized lists of length 100k, I found the average time for the first to complete was 0.047 seconds, and the average time for the second was 0.043

Is my assumption correct (the first is just syntactic sugar for the second), or is there something more interesting going on here?

Rushabh Mehta
  • 1,529
  • 1
  • 13
  • 29
  • 3
    https://stackoverflow.com/questions/3653298/concatenating-two-lists-difference-between-and-extend, does this answer your question? – krxat Jul 31 '20 at 18:47
  • 1
    When I try it out I consistently get `+=` being faster than `extend`. Not sure how you're getting `extend` to be faster. – khelwood Jul 31 '20 at 18:48
  • 1
    Maybe try to increase the number of trials (e.g: 500) and calculate the standard deviation in addition to the mean time. You also need to determine if the difference between 0.043 and 0.047 is signifcant (not just statistical error) and consistent across repeated tests. – Daniser Jul 31 '20 at 18:48

1 Answers1

0

'+=' is a 'basic operation' in Python so to say, while '.extend' is a function that needs to be called and then perform some 'basic' operations, perhaps just like '+='. That's why .extend takes more time.

MercifulSory
  • 337
  • 1
  • 14