Lists in Python

Lists in Python

![Python list][python_list]

A list in Python is an ordered collection of items that can be of different types, including numbers, strings, and even other lists. Lists are a very useful data structure in Python and are used to store and manipulate data in a variety of programs and applications.

Creating a List

To create a list in Python, you can use square brackets [] and separate the items with commas. For example:

my_list = [1, 2, 3, 4, 5]

You can also create a list of strings:

my_list = ['a', 'b', 'c', 'd', 'e']

Or a list of mixed data types:

my_list = [1, 'a', 2, True, 'b', 3, 'c']
print(my_list[3]) # Output: True

Accessing List Items

You can access the items in a list by referring to their index number. The index numbers start at 0 for the first item, 1 for the second item, and so on.

my_list = ['a', 'b', 'c', 'd', 'e']

# Get the first item (index 0)
print(my_list[0])  # Output: 'a'

# Get the second item (index 1)
print(my_list[1])  # Output: 'b'

You can also use negative index numbers to access items from the end of the list. For example, index -1 refers to the last item, index -2 refers to the second last item, and so on.

my_list = ['a', 'b', 'c', 'd', 'e']

# Get the last item (index -1)
print(my_list[-1])  # Output: 'e'

# Get the second last item (index -2)
print(my_list[-2])  # Output: 'd'

Modifying List Items

You can modify the items in a list by assigning a new value to them using the index number.

my_list = ['a', 'b', 'c', 'd', 'e']

# Modify the second item (index 1)
my_list[1] = 'f'

print(my_list)  # Output: ['a', 'f', 'c', 'd', 'e']

Adding Items to a List

There are several ways to add items to a list in Python.

Appending Items

You can use the append() method to add an item to the end of the list.

my_list = ['a', 'b', 'c', 'd', 'e']

# Add an item to the end of the list
my_list.append('f')

print(my_list)  # Output: ['a', 'b', 'c', 'd', 'e', 'f']

Inserting Items

You can use the insert() method to insert an item at a specific index. The insert() method takes in two parameters insert(index, item).

my_list = ['a', 'b', 'c', 'd', 'e']

# Add item to the 3rd index
my_list.insert(3, 'z')
print(my_list) # Output: ['a', 'b', 'c', 'z', 'd', 'e']

Removing Items from a list

There 3 ways to remove an element from a list,

  1. The remove(x) method is used to remove an item(x) from a list, but it raises a value error when the item is not found. Example:

     my_list = ['a', 'b', 'c', 'd', 'e']
     # Remove b from the list.
     my_list.remove('b')
     print(my_list) #Output: ['a', 'c', 'd', 'e']
     # Remove g from the list
     try:
         my_list.remove('g') #Output: ValueError: list.remove(x): x not in list
     except ValueError:
         print('ValueError: list.remove(x): x not in list')
    

    Notice that the last line produced ValueError, this is because 'g' is not in any index of the list.

  2. The pop(index) method is used to remove an element from a list and also return the element, If no index is specified pop() removes the last element by default, Example:

     my_list = ['a', 'b', 'c', 'd', 'e']
     # Remove 'c' from the list.
     my_list.pop(2)
     print(my_list) #Output: ['a', 'b','d', 'e']
     # Get the last element
     last = my_list.pop()
     print(my_list) # Output: ['a' ,'b' ,'c' ,'d']
     print(last) #Output: e
    

    'e' was able to be printed because pop() was used to remove it, It would return None if it were to be the remove() method we used to remove it.

  3. The clear() method is used to remove all the elements of the list, It is the same as using the del keyword, Example:

     my_list = ['a', 'b', 'c', 'd', 'e']
     # Remove all elements of the list
     my_list.clear() # same as del my_list[:]
     # The result will be an empty list
     print(my_list) # Output: []
    

    Reverse a list

    To reverse a list you can use the reverse() method, for Example.

my_list = ['a', 'b', 'c', 'd', 'e']
my_list.reverse()
print(my_list) # Output: ['e', 'd', 'c', 'b', 'a']

Other import methods are:

#copy() to copy a list
my_list = ['a', 'b', 'c', 'd', 'e']
new_list = my_list.copy()
print(new_list) # Output: ['a', 'b', 'c', 'd', 'e']

#sort() to sort the list
my_list = ['e', 'd', 'c', 'b', 'a']
my_list.sort()
print(my_list) # Output: ['a', 'b', 'c', 'd', 'e']

#count(x) to get the number of times an item(x) occurs
my_list = ['e', 'd', 'c', 'b', 'a', 'c']
item_cnt = my_list.count('c')
print(item_cnt) #Output: 2

#index(x) to get the index of x 
my_list = ['e', 'd', 'c', 'b', 'a', 'c']
item_index = my_list.index('b')
print(item_index) # Output: 3

List Slicing

In Python, you can use list slicing to extract elements from a list. List slicing is a concise way to create a new list from an existing list, and it allows you to specify the indices that you want to extract. Here is the basic syntax for list slicing in Python:

new_list = old_list[start:end:step]

Here are the meanings of the parameters:

  • start: The index of the first element that you want to extract (inclusive).

  • end: The index of the last element that you want to extract (exclusive).

  • step: The number of indices to skip between elements.

Here are some examples of how you can use list slicing in Python:

# Extract the first three elements from a list
old_list = [1, 2, 3, 4, 5]
new_list = old_list[0:3]
print(new_list)  # Output: [1, 2, 3]

# Extract the last two elements from a list
old_list = [1, 2, 3, 4, 5]
new_list = old_list[-2:]
print(new_list)  # Output: [4, 5]

# Extract every other element from a list
old_list = [1, 2, 3, 4, 5]
new_list = old_list[::2]
print(new_list)  # Output: [1, 3, 5]

Those are the fundamentals of manipulating lists in python, I hope you have gotten a firm grasp of it.