„Python“ sąrašo priedas „VS“ „Python“ sąrašo išplėtimas - skirtumas, paaiškintas masyvo metodo pavyzdžiais

? Sveiki

Jei norite sužinoti, kaip dirbti su .append()ir .extend()ir suprasti jų skirtumus, tada turite ateiti į tinkamą vietą. Tai yra galingi sąrašų metodai, kuriuos tikrai naudosite savo „Python“ projektuose.

Šiame straipsnyje sužinosite:

  • Kaip ir kada naudoti .append()metodą.
  • Kaip ir kada naudoti .extend()metodą.
  • Pagrindiniai jų skirtumai.

Pradėkime. ✨

? Pridėti

Pažiūrėkime, kaip .append()metodas veikia užkulisiuose.

Naudojimo atvejai

Turėtumėte naudoti šį metodą, kai norite pridėti vieną elementą prie sąrašo pabaigos .

? Patarimai: Galite pridėti bet kokio tipo duomenų elementus, nes sąrašuose gali būti įvairių tipų elementai.

Sintaksė ir argumentai

Norėdami iškviesti .append()metodą, turėsite naudoti šią sintaksę:

Iš kairės į dešinę:

  • Sąrašas bus pakeistas. Paprastai tai yra kintamasis, nurodantis sąrašą.
  • Taškas, po kurio nurodomas metodo pavadinimas .append().
  • Skliaustuose elementas, kuris bus pridėtas prie sąrašo pabaigos.

? Patarimai: taškas yra labai svarbus. Tai vadinama „taškų žymėjimu“. Taške iš esmės sakoma „iškvieskite šį metodą į šį konkretų sąrašą“, todėl metodo poveikis bus taikomas sąrašui, esančiam prieš tašką.

Pavyzdžiai

Štai pavyzdys, kaip naudoti .append():

# Define the list >>> nums = [1, 2, 3, 4] # Add the integer 5 to the end of the existing list >>> nums.append(5) # See the updated value of the list >>> nums [1, 2, 3, 4, 5]

? Patarimai: kai naudojate .append()originalų sąrašą, jis yra pakeistas. Metodas nesukuria sąrašo kopijos - jis mutuoja pirminį sąrašą atmintyje.

Apsimeskime, kad atliekame tyrimą ir norime išanalizuoti duomenis, surinktus naudojant „Python“. Turime pridėti naują matavimą prie esamo verčių sąrašo.

Kaip mes tai darome? Mes naudojame .append()metodą!

Tai galite pamatyti čia:

# Existing list >>> nums = [5.6, 7.44, 6.75, 4.56, 2.3] # Add the float (decimal number) to the end of the existing list >>> nums.append(7.34) # See the updated value of the list >>> nums [5.6, 7.44, 6.75, 4.56, 2.3, 7.34]

Prilygsta ...

Jei esate susipažinę su eilutės, sąrašo ar paketo pjaustymu, tai, kas .append()iš tikrųjų yra užkulisiuose, yra tolygu:

a[len(a):] = [x]

Šiuo pavyzdžiu galite pamatyti, kad jie yra lygiaverčiai.

Naudojant .append():

>>> nums = [5.6, 7.44, 6.75, 4.56, 2.3] >>> nums.append(4.52) >>> nums [5.6, 7.44, 6.75, 4.56, 2.3, 4.52]

Sąrašo pjaustymas:

>>> nums = [5.6, 7.44, 6.75, 4.56, 2.3] >>> nums[len(nums):] = [4.52] >>> nums [5.6, 7.44, 6.75, 4.56, 2.3, 4.52]

Sekos pridėjimas

Ką tu manai apie šį pavyzdį? Kaip manote, kokia bus produkcija?

>>> nums = [5.6, 7.44, 6.75, 4.56, 2.3] >>> nums.append([5.67, 7.67, 3.44]) >>> nums # OUTPUT?

Ar tu pasiruošęs? Tai bus išvestis:

[5.6, 7.44, 6.75, 4.56, 2.3, [5.67, 7.67, 3.44]]

Galbūt klausiate, kodėl visas sąrašas buvo pridėtas kaip vienas elementas? Taip yra todėl, kad .append()metodas įtraukia visą elementą į sąrašo pabaigą. Jei elementas yra seka, tokia kaip sąrašas, žodynas ar paketas, visa seka bus įtraukta kaip vienas esamo sąrašo elementas.

Čia mes turime kitą pavyzdį (žemiau). Tokiu atveju elementas yra paketas ir jis pridedamas kaip vienas sąrašo elementas, o ne kaip atskiri elementai:

>>> names = ["Lulu", "Nora", "Gino", "Bryan"] >>> names.append(("Emily", "John")) >>> names ['Lulu', 'Nora', 'Gino', 'Bryan', ('Emily', 'John')]

? Pratęskite

Dabar pasinerkime į .extend()metodo funkcionalumą .

Naudojimo atvejai

Turėtumėte naudoti šį metodą, jei jums reikia pridėti kelis elementus prie sąrašo kaip atskirus elementus .

Let me illustrate the importance of this method with a familiar friend that you just learned: the .append() method. Based on what you've learned so far, if we wanted to add several individual items to a list using .append(), we would need to use .append() several times, like this:

# List that we want to modify >>> nums = [5.6, 7.44, 6.75, 4.56, 2.3] # Appending the items >>> nums.append(2.3) >>> nums.append(9.6) >>> nums.append(4.564) >>> nums.append(7.56) # Updated list >>> nums [5.6, 7.44, 6.75, 4.56, 2.3, 2.3, 9.6, 4.564, 7.56]

I'm sure that you are probably thinking that this would not be very efficient, right? What if I need to add thousands or millions of values? I cannot write thousands or millions of lines for this simple task. That would take forever!

So let's see an alternative. We can store the values that we want to add in a separate list and then use a for loop to call .append() as many times as needed:

# List that we want to modify >>> nums = [5.6, 7.44, 6.75, 4.56, 2.3] # Values that we want to add >>> new_values = [2.3, 9.6, 4.564, 7.56] # For loop that is going to append the value >>> for num in new_values: nums.append(num) # Updated value of the list >>> nums [5.6, 7.44, 6.75, 4.56, 2.3, 2.3, 9.6, 4.564, 7.56]

This is more efficient, right? We are only writing a few lines. But there is an even more efficient, readable, and compact way to achieve the same purpose: .extend()!

>>> nums = [5.6, 7.44, 6.75, 4.56, 2.3] >>> new_values = [2.3, 9.6, 4.564, 7.56] # This is where the magic occurs! No more for loops >>> nums.extend(new_values) # The list was updated with individual values >>> nums [5.6, 7.44, 6.75, 4.56, 2.3, 2.3, 9.6, 4.564, 7.56]

Let's see how this method works behind the scenes.

Syntax and Arguments

To call the .extend() method, you will need to use this syntax:

From Left to Right:

  • The list that will be modified. This is usually a variable that refers to the list.
  • A dot . (So far, everything is exactly the same as before).
  • The name of the method extend. (Now things start to change...).
  • Within parentheses, an iterable (list, tuple, dictionary, set, or string) that contains the items that will be added as individual elements of the list.

? Tips: According to the Python documentation, an iterable is defined as "an object capable of returning its members one at a time". Iterables can be used in a for loop and because they return their elements one at a time, we can "do something" with each one of them, one per iteration.

Behind the Scenes

Let's see how .extend() works behind the scenes. Here we have an example:

# List that will be modified >>> a = [1, 2, 3, 4] # Sequence of values that we want to add to the list a >>> b = [5, 6, 7] # Calling .extend() >>> a.extend(b) # See the updated list. Now the list a has the values 5, 6, and 7 >>> a [1, 2, 3, 4, 5, 6, 7]

You can think of .extend() as a method that appends the individual elements of the iterable in the same order as they appear.

In this case, we have a list a = [1, 2, 3, 4] as illustrated in the diagram below. We also have a list b = [5, 6, 7] that contains the sequence of values that we want to add. The method takes each element of b and appends it to list a in the same order.

After this process is completed, we have the updated list a and we can work with the values as individual elements of a.

? Tips: The list b used to extend list a remains intact after this process. You can work with it after the call to .extend(). Here is the proof:

>>> a = [1, 2, 3, 4] >>> b = [5, 6, 7] >>> a.extend(b) >>> a [1, 2, 3, 4, 5, 6, 7] # List b is intact! >>> b [5, 6, 7]

Examples

You may be curious to know how the .extend() method works when you pass different types of iterables. Let's see how in the following examples:

For tuples:

The process works exactly the same if you pass a tuple. The individual elements of the tuple are appended one by one in the order that they appear.

# List that will be extended >>> a = [1, 2, 3, 4] # Values that will be added (the iterable is a tuple!) >>> b = (1, 2, 3, 4) # Method call >>> a.extend(b) # The value of the list a was updated >>> a [1, 2, 3, 4, 1, 2, 3, 4]

For sets:

The same occurs if you pass a set. The elements of the set are appended one by one.

# List that will be extended >>> a = [1, 2, 3, 4] # Values that will be appended (the iterable is a set!) >>> c = {5, 6, 7} # Method call >>> a.extend(c) # The value of a was updated >>> a [1, 2, 3, 4, 5, 6, 7]

For strings:

Strings work a little bit different with the .extend() method. Each character of the string is considered an "item", so the characters are appended one by one in the order that they appear in the string.

# List that will be extended >>> a = ["a", "b", "c"] # String that will be used to extend the list >>> b = "Hello, World!" # Method call >>> a.extend(b) # The value of a was updated >>> a ['a', 'b', 'c', 'H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']

For dictionaries:

Dictionaries have a particular behavior when you pass them as arguments to .extend(). In this case, the keys of the dictionary are appended one by one. The values of the corresponding key-value pairs are not appended.

In this example (below), the keys are "d", "e", and "f". These values are appended to the list a.

# List that will be extended >>> a = ["a", "b", "c"] # Dictionary that will be used to extend the list >>> b = {"d": 5, "e": 6, "f": 7} # Method call >>> a.extend(b) # The value of a was updated >>> a ['a', 'b', 'c', 'd', 'e', 'f']

Equivalent to...

What .extend() does is equivalent to a[len(a):] = iterable. Here we have an example to illustrate that they are equivalent:

Using .extend():

# List that will be extended >>> a = [1, 2, 3, 4] # Values that will be appended >>> b = (6, 7, 8) # Method call >>> a.extend(b) # The list was updated >>> a [1, 2, 3, 4, 6, 7, 8] 

Using list slicing:

# List that will be extended >>> a = [1, 2, 3, 4] # Values that will be appended >>> b = (6, 7, 8) # Assignment statement. Assign the iterable b as the final portion of the list a >>> a[len(a):] = b # The value of a was updated >>> a [1, 2, 3, 4, 6, 7, 8]

The result is the same, but using .extend() is much more readable and compact, right? Python truly offers amazing tools to improve our workflow.

? Summary of their Differences

Now that you know how to work with .append() and .extend(), let's see a summary of their key differences:

  • Effect: .append() adds a single element to the end of the list while .extend() can add multiple individual elements to the end of the list.
  • Argument: .append() takes a single element as argument while .extend() takes an iterable as argument (list, tuple, dictionaries, sets, strings).

I really hope that you liked my article and found it helpful. Now you can work with .append() and .extend() in your Python projects. Check out my online courses. Follow me on Twitter. ⭐️