python list

Table of contents:

  1. What is the Python list?
  2. Creating lists
  3. Accessing list elements
  4. List slicing
  5. Modifications of list elements
    • Changing
    • Adding
    • Deleting
  6. Python list methods
  7. Conclusion

In this tutorial, we will learn all there is to know about Python lists, including how to create them, change their elements, delete them, and perform other modifications with examples.

What is the Python list?

A list is an ordered sequence of elements. A list can have any number of elements, and they can be of different data types. A list is very flexible, which means that we can make different changes to the elements once the list is created.


Creating lists

The declaration of a list is quite simple. Elements separated by commas , are enclosed in brackets [ ]. Let’s see an example of creating lists with items of different Data Types:

# Creating an empty list
list_emp = []
print(list_emp)

# Creating list of integers
list_int = [7, 6, 5, 4, 3]
print(list_int)

# Creating list of mixed Data Types
list_mix = [69, "I like it!", 3.14]
print(list_mix)

# Creating a nested list
list_nested = ["sun", [1, 2, 3], ['Moon']]
print(list_nested)

Output:

[] [7, 6, 5, 4, 3] [69, ‘I like it!’, 3.14] [‘sun’, [1, 2, 3], [‘Moon’]]

Accessing list elements

Since a list is an ordered collection, we can access its elements by index method. An index is the position of an item in a list. Lists have an index of zero. In other words, the first element in a list always has an index of 0, the second element has an index of 1, and so on. To access an item, its index is enclosed in brackets (ex: list name [index]). For example, the following shows how to access the first element of a list of numbers:

# List with 10 mixed values in range 0-9
my_list = [1, 2, 3, 4, 'five', 'six', 'seven', 8.0, 9.0, 10.0]

# Printing fives element of the list using indexing [4]
print('Element with index 4 -',my_list[4])

Output:

Element with index 4 – five

Trying to access indexes out of the range of the list will raise an IndexError. Let’s check it:


# List with 10 mixed values in range 0-9
my_list = [1, 2, 3, 4, 'five', 'six', 'seven', 8.0, 9.0, 10.0]

# Printing element of the list with index [10]
print(my_list[10])

Output:

Traceback (most recent call last): File ““, line 5, in IndexError: list index out of range

Also, the index must always be an integer. We cannot use float or other types, it will cause a TypeError. Here is the example of it:

# List with 10 mixed values in range 0-9
my_list = [1, 2, 3, 4, 'five', 'six', 'seven', 8.0, 9.0, 10.0]

# Printing element of the list with index [6.5]
print(my_list[6.5])

Output:

Traceback (most recent call last): File ““, line 5, in TypeError: list indices must be integers or slices, not float

Nested lists require nested indexing. Let’s see how it works in Python:


# Nested list
nest_list = ['sun', [2, 0, 1, 7],[6.78, 9.0, 11.1]]

# Nested indexing
# [0] adresses to the 1st element of the list['sun']
# [2] addresses to the 3rd element of 'sun'
print(nest_list[0][2]) 

print(nest_list[1][3])

print(nest_list[2][0])

Output:

n 7 6.78

Python allows us to use a negative index for its sequences. The index -1 refers to the last element, -2 to the second last element, and so on.


# List with 10 mixed values in range -1 to -10
my_list = [1, 2, 3, 4, 'five', 'six', 'seven', 8.0, 9.0, 10.0]

# Printing element using negative index [-7]
print('Element with index -7 is',my_list[-7])

Output:

Element with index -7 is 4

List slicing

We can access a range of elements in the list with the slicing operator (:). See example of using slicing below:


# Mixed list
my_list = [1, 2, 3, 4, 'five', 'six', 'seven', 8.0, 9.0, 10.0]

# Elements from index 2 to index 4
print(my_list[4:7])

# Elements from index 5 to end
print(my_list[6:])

# Elements beginning to end
print(my_list[:])

Output:

[‘five’, ‘six’, ‘seven’] [‘seven’, 8.0, 9.0, 10.0] [1, 2, 3, 4, ‘five’, ‘six’, ‘seven’, 8.0, 9.0, 10.0]

Modifications of list elements

The list is dynamic and flexible. This means that we can change items in the list, add new items, and remove items from the list.

Changing

To change an element in the list, we assign it a new value using the following syntax:

list[index] = new_value.

# List of odd numbers
odd = [2,3, 5, 7, 9, 11]

print('Before changing:',odd)

# Changing 1st element to new one
odd[0] = 1

print('After changing:',odd)

Output:

Before changing: [2, 3, 5, 7, 9, 11] After changing: [1, 3, 5, 7, 9, 11]

Adding

We can add a single item to the end list with the append() method or add multiple items with the extend() method. To add new element to any place we can use insert() method. For example:


# List of odd numbers
odd = [1, 3, 5, 7, 9, 11]
print('Before adding:',odd)

# Using append() method to add a new element to the list
odd.append(13)
print('After adding 1 element:',odd)

# Using exted() method to add 3 new element to the list
odd.extend([15, 17, 19])
print('After adding several element:',odd)

# Using insert() method to add a new element to any place of the list
odd.insert(5,11)
print('After adding a new element to the 5th index place:',odd)

Output:

Before adding: [1, 3, 5, 7, 9, 11] After adding 1 element: [1, 3, 5, 7, 9, 11, 13] After adding several element: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19] After adding a new element to the 5th index place: [1, 3, 5, 7, 9, 11, 11, 13, 15, 17, 19]

Deleting

There are several methods we can use to remove some or all of the items in a list.

For example, the del operator allows you to remove an item from a list by specifying its position. To remove an item by value, the remove() method is used. The pop() method removes the last item from the list and returns this item.   And if we want to remove the whole list, we use clear().

Let’s look at examples of how to use all these methods:


# List of odd numbers
odd = [1, 3, 5, 7, 9, 11]
print('Before deleting:',odd)

# Using del to remove element by index
del odd[2]
print('After deleting an element:',odd)

# Using remove() to delete specific value from the list
odd.remove(9)
print('After deleting a specific element:',odd)

# Using pop() method to delete
num = odd.pop(2)
print('What we\'re deleting -',num)
print('After deleting it:',odd)

# Deleting all elements of the list using clear()
odd.clear()
print('After deleting all elements:',odd)

Output:

Before deleting: [1, 3, 5, 7, 9, 11] After deleting an element: [1, 3, 7, 9, 11] After deleting a specific element: [1, 3, 7, 11] What we’re deleting – 7 After deleting it: [1, 3, 11] After deleting all elements: []

Python list methods

In the examples above we got familiar with some list methods like index(), append(), extend(), insert(), remove(), pop(), clear(), but they’re not the only ones. Let’s look at the other methods that we can use with Python lists:

Method Description
copy() Returns a shallow copy of a list
count() Counts how many times element occurs in a list
reverse() Reverses elements of a list
sort() Sorts elements of a list

Here is the example of using these methods on a list:


odd = [11, 3, 5, 3, 5, 7, 9, 11, 11, 100]
print('Our list -',odd)

# Using copy() to copy the list
print('Copy of "odd" -',odd.copy())

# Using count() to find out how many times we used 11 in the list
print('How many times 11 is used in the list? -',odd.count(11))

# Using reverse() to reverse the list
odd.reverse()
print('Reversed version of the list -',odd)

# Usinf sort() to sort our list elements in ascending order(not values)
odd.sort()
print('Sorted version of the list -',odd)

Output:

Our list – [11, 3, 5, 3, 5, 7, 9, 11, 11, 100] Copy of “odd” – [11, 3, 5, 3, 5, 7, 9, 11, 11, 100] How many times 11 is used in the list? – 3 Reversed version of the list – [100, 11, 11, 9, 7, 5, 3, 5, 3, 11] Sorted version of the list – [3, 3, 5, 5, 7, 9, 11, 11, 11, 100]

Conclusion

In this tutorial, we discussed how to create a list in Python, with the same and different Data Types. Moreover, we learned how to access a certain element in lists using the indexing method. We also covered different methods of modifying lists, such as adding new items, removing items, and so on.

Leave a Reply