Adding Items to a List

List’s versatility to comes from its ability to contain information and add on information. This lesson covers how to do so.

Adding an Item to the End of a List

This is the safest and the recommended way to add values: add the new value to the end.

.append(item) is method that adds the given item to the end of a list.

# .append() Example

a_list = ['apple', 'oranges']
a_list.append('kiwi')
a_list.append('honeydew')
print('a_list:', a_list)
a_list: ['apple', 'oranges', 'kiwi', 'honeydew']

Adding an Item at a Location

This technique can cause potential issues; however, it does exist!

.insert(location, item) will add the given item at the specified integer location.

NOTES:

  • If the location is beyond the size, it will add it to the end

  • Location can be negative

  • If the location already has a value, it will shift everything at the location onwards to the right to add the item

Combining Lists

There are multiple ways to combine lists!

  1. Manipulate a list with all the value from another at the tail-end.

.extend(list) is a method that adds all the items from the given list argument to its list.

  1. Use the + operator to generate a new list

The + operator is the concatenation operator much like how strings have one.

Instead of manipulate the left operand, it will return a new list.

  1. Preserve the variable but generate a new list += operator

We can also use the += assignment operator to concatenate then assign.

List Repetition Operation

* operator helps us repeat a list.

Example:

Last updated