List

List methods

list methods modify the target list in place. They do not return a new list. We do not need to use assignment operators such as =.

append()

You can use append() to added an element to the end of a list.

age = [23, 45, 89, 18, 24, 29, 36]
age.append(57)

Output:

[23, 45, 89, 18, 24, 29, 36, 57]

A list can be added to another list, but it will append the list as a sublist rather than extending the elements within the main list (it is added as a single object).

age = [23, 45, 89, 18, 24, 29, 36]
age.append([57, 34, 19])

Output:

[23, 45, 89, 18, 24, 29, 36, [57, 34, 19]]

extend()

Similar to append(), extend() also adds element/s to the end of a list and only modifies the original list. the argument between () should be an iterable, i.e., adding an element at a time.

age = [23, 45, 89, 18, 24, 29, 36]
age.extend([57, 34, 19])

Output:

[23, 45, 89, 18, 24, 29, 36, 57, 34, 19]

You can see the difference between append() and extend() methods when adding a list to a list. append() adds as a sublist but extend() adds an element at a time

insert()

You can insert one element at a desired location by using the method insert(). insert() takes two arguments:

  1. The index location to add the element and
  2. the element (string, float, integer etc).

The newly inserted element will push the elements from the index insert location to the right.

['Krakow', 'Warsaw', 'Lodz', 'Kielce']
my_cities.insert(2, 'Poznan')

Output:

['Krakow', 'Warsaw', 'Poznan', 'Lodz', 'Kielce']

pop()

The pop() removes and returns the last element when no index is provided. You can use pop() with an index to remove an element at the given index. pop() is helpful because it may insert or remove an element from only one end, as a result, lists can be implemented as stacks (last-in, first-out).

my_cities = ['Krakow', 'Warsaw', 'Warsaw', 'Lodz', 'Kielce']

# pop() returns the last element
my_cities.pop()

# Above list misses the last element
print(my_cities)

Outputs:

# Output for pop()
'Kielce'

# Our list after applying pop()
['Krakow', 'Warsaw', 'Warsaw', 'Lodz']

remove()

You can use remove() method to remove a given element. You have to provide the element (not its index).

my_cities = ['Krakow', 'Warsaw', 'Lodz', 'Kielce']
my_cities.remove('Krakow')

Output:

['Warsaw', 'Lodz', 'Kielce']

remove() removes only the FIRST occurrence of the element.

my_cities = ['Krakow', 'Warsaw', 'Warsaw', 'Lodz', 'Kielce']
my_cities.remove('Warsaw')

Output:

['Krakow', 'Warsaw', 'Lodz', 'Kielce']