Solved

append() vs extend() — added a list inside my list

CharlieHOP
items = [1, 2]
items.append([3, 4])
print(items)  # [1, 2, [3, 4]]

I wanted [1, 2, 3, 4].

5

Comments 4

Join the discussion

Already have an account? Log in

  1. TomBecker Solutionreplies: 1

    append adds its argument as one element. extend adds each element of an iterable:

    items.extend([3, 4])   # [1, 2, 3, 4]

    items += [3, 4] does the same as extend.

    10
    1. HenryWrites

      Watch out: items.extend("abc") adds 'a', 'b', 'c' separately, because a string is iterable.

      2
      1. LiamByte

        pop() is also nice for queues, but pop(0) is slow on big lists. collections.deque is made for that.

        1