Home > OS >  If I am appending multiple elements to a list in python, is it more worth putting them all into a li
If I am appending multiple elements to a list in python, is it more worth putting them all into a li

Time:01-25

For example:

lst.append(x)
lst.append(25)
lst.append(y)

Would it be better to write this:

lst.extend([x, 25, y])

CodePudding user response:

I would argue that it depends on the nature of the list being appended. Given that the list is fixed, meaning that you are sure what elements are in it, it would make sense to use the latter version (lst.extend([x, 25, y])).

Given that you want to append elements depending on certain logical conclusions, you should probably append elements separately, except if you are sure that two elements are always being appended together.

What I mean by this is that if you want to append elements to the list depending on logic such as if-statements, where one if statement might append one element to the list but not another, it makes sense to split the elements being appended into several separate elements. If you know on the other hand that all elements will be added at the same time, you would much rather use the latter version, as it makes your code more compact and easier to read.

extend() also runs faster than append(), if that is what you are after

CodePudding user response:

If you are adding one element to the list use append each time. If instead you have a list of several elements to add to the list use extend which will effectively append each of the iterables of the argument provided.

  •  Tags:  
  • Related