Efficient List Manipulation in Python: When to Use ‘append’ and ‘extend’

Let’s say I created a function in Python to deal a group of cards. The Ace is represented by 11, Jack, Queen, and King by 10 and the rest of the deck shows its face value.

This function will randomly take an element from the list named cards and return a list with a number. Using a for loop with a specific range you could generate as many numbers as you wish.

In this example, I created a list called: “user_card” to add the number of cards dealt.

Input:

Output : for card in range(2):

Output : for card in range(3):

The next step was asking the player if he wanted an additional card, showing him the new deck, and sum the final score.

My initial idea was to use the function: “.append” to add at the end of the list: “user_card” the new card but the output showed an error.

Input:

Output: TypeError: unsupported operand type(s) for +: ‘int’ and ‘list’

The function named: “deal_card( )” creates a list named: “dealt_cards”. then includes the random number from the list: “cards” inside the list: “dealt_cards” and returns it as a list.

When the function “dealt_card” is called and the “.append” list function is used, it will include the “dealt_cards” list inside the “user_card” list.

After that, the “sum( )” function tries to add all the values ​​inside the list and the error occurs. We need to change the list function: “.append” to “.extend”:

Input:­­

Output:

The following is an excellent explanation to delve deeper into the difference.

Understanding the Difference Between ‘list.append‘ and ‘list.extend‘ in Python

When working with lists in Python, you might encounter two methods for adding elements to a list: append() and extend(). While they may seem similar at first glance, they serve different purposes and have distinct behaviors.

list.append()

The append() method adds its argument as a single element to the end of a list. The length of the list increases by one.

Example:

In this example, the string 'cherry' is added as a single element at the end of the fruits list.

list.extend()

The extend() method iterates over its argument, adding each element to the list. The length of the list increases by however many elements were in the iterable argument.

Example:

Here, the elements 'cherry' and 'date' from the list ['cherry', 'date'] are added individually to the fruits list.

Key Differences

  • Purpose: Use append() when you need to add a single item to the list. Use extend() when you need to combine another list or iterable with the existing list.
  • Behavior: append() treats its argument as a single entity and adds it to the list as-is. extend() iterates over its argument, adding each element to the list.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *