Lists in Python

0
407
Lists in Python
Lists in Python

A list in Python is a mutable and ordered sequence of elements. It is a built-in data structure and is one of several compound data types supported by Python. Each element that is contained in a list is called an item. A list can contain items of different data types which makes lists very powerful. Python lists can also contain duplicate items.

1. Creating a List in Python

A Python list is created by specifying items as comma-separated values inside square brackets [ ].

>>> fruits = [] # Creating an empty list
>>> print(fruits)
[]
>>> fruits = ["apple", "mango", "banana"] # Creating a list that contains items of "string" data type
>>> print(fruits)
['apple', 'mango', 'banana']
>>> my_list = [1, "cricket", 3.0, True] # Creating a list that contains items of multiple data types
>>> print(my_list)
[1, 'cricket', 3.0, True]

2. List Indexing

Like strings, lists in Python can also be indexed. Each item of a list corresponds to an index number. The first item has an index 0.

Accessing List Items Using a Positive Index Number

We can use a positive index number in square brackets and access a list item as shown below:

>>> fruits = ["apple", "mango", "banana"]
>>> print(fruits[0])
apple
>>> print(fruits[2])
banana

Accessing List Items Using a Negative Index Number

Similar to strings, Python lists also support negative index numbers. We can use negative indices with lists to start counting from the end of the list, starting at the index number -1.

>>> fruits = ["apple", "mango", "banana"]
>>> print(fruits[-1])
banana
>>> print(fruits[-3])
apple

3. Modifying Items in a List Using Index Numbers

Since lists in Python are mutable, we can modify the items in a list. This is done using the assignment operator as shown below:

>>> fruits = ["apple", "mango", "banana"]
>>> print(fruits)
['apple', 'mango', 'banana']
>>> fruits[1] = "orange" # Change second item from "mango" to "orange"
>>> print(fruits)
['apple', 'orange', 'banana']

4. Modifying Lists with + and += Operators

We can concatenate two or more lists together using the + operate as shown below:

>>> fruits1 = ["apple", "mango", "banana"]
>>> fruits2 = ["orange", "pineapple", "grape", "papaya"]
>>> fruits = fruits1 + fruits2
>>> print(fruits)
['apple', 'mango', 'banana', 'orange', 'pineapple', 'grape', 'papaya']

The + operator can also be used to add an item or multiple items (in list form) to the end of a list as shown below:

>>> fruits = ["apple", "mango", "banana"]
>>> fruits = fruits + ["orange"] # Adding a single list item at the end of the list "fruits"
>>> print(fruits)
['apple', 'mango', 'banana', 'orange']
>>> fruits = ["apple", "mango", "banana"]
>>> fruits = fruits + ["orange", "pineapple"] # Adding multiple list items at the end of the list "fruits"
>>> print(fruits)
['apple', 'mango', 'banana', 'orange', 'pineapple']

We can also use the += compound operator with lists as shown below:

>>> fruits = ["apple", "mango", "banana"]
>>> fruits += ["orange", "pineapple"]
>>> print(fruits)
['apple', 'mango', 'banana', 'orange', 'pineapple']

5. Modifying Lists with * and *= Operators

We can multiply lists using the * operate as shown below:

>>> fruits = ["apple", "mango", "banana"]
>>> fruits = 3 * fruits
>>> print(fruits)
['apple', 'mango', 'banana', 'apple', 'mango', 'banana', 'apple', 'mango', 'banana']

We can also use the *= compound operator with lists as shown below:

>>> fruits = ["apple", "mango", "banana"]
>>> fruits *= 3
>>> print(fruits)
['apple', 'mango', 'banana', 'apple', 'mango', 'banana', 'apple', 'mango', 'banana']

6. Removing an Item from a List

We can use the ‘del’ statement to remove an item from a list at a specified index number as shown below:

>>> fruits = ["apple", "mango", "banana", "orange", "pineapple", "grape", "papaya"]
>>> del fruits[2]
>>> print(fruits)
['apple', 'mango', 'orange', 'pineapple', 'grape', 'papaya']

7. Nested Lists

We can create a list which contains another list as an item. A list within another list is called a nested list.

>>> fruits = ["apple", "mango", "banana", ["orange", "pineapple", "grape"], "papaya"]
>>> print(fruits)
['apple', 'mango', 'banana', ['orange', 'pineapple', 'grape'], 'papaya']
>>> print(fruits[3])
['orange', 'pineapple', 'grape']
>>> print(fruits[3][1])
pineapple

8. List Slicing

Like strings, lists in Python can also be sliced. A slice can be created by using a range of index numbers separated by a colon in the format [x:y]. Here, the first index number is inclusive and specifies where the slice starts from. The second index number is exclusive and specifies where the slice ends.

>>> fruits = ["apple", "mango", "banana", "orange", "pineapple", "grape", "papaya"]
>>> print(fruits[1:4])
['mango', 'banana', 'orange']

We can include either end of a list by omitting one of the index numbers. For example, to create a slice that starts at the beginning of the list and ends in the middle, we have to specify only the index number after the colon as shown below:

>>> fruits = ["apple", "mango", "banana", "orange", "pineapple", "grape", "papaya"]
>>> print(fruits[:3])
['apple', 'mango', 'banana']

Likewise, we can create a slice that starts in the middle of the list and includes each item until the end of the list by specifying only the index number before the colon as shown below:

>>> fruits = ["apple", "mango", "banana", "orange", "pineapple", "grape", "papaya"]
>>> print(fruits[5:])
['grape', 'papaya']

We can also omit both the index numbers to create a slice that starts at the head of the list and ends at the tail of the list. This approach is helpful in combination with the stride parameter which is discussed below in this article.

>>> fruits = ["apple", "mango", "banana", "orange", "pineapple", "grape", "papaya"]
>>> print(fruits[:])
['apple', 'mango', 'banana', 'orange', 'pineapple', 'grape', 'papaya']

It is also possible to use negative index numbers for list slicing.

>>> fruits = ["apple", "mango", "banana", "orange", "pineapple", "grape", "papaya"]
>>> print(fruits[-5:-2])
['banana', 'orange', 'pineapple']

Specifying Stride While Slicing Lists

In the examples above, we have used two index numbers to slice a list. It is also possible to use a third parameter called ‘stride’ which specifies how many items to move forward after the first item has been retrieved from the list. The default value of stride is 1.

>>> fruits = ["apple", "mango", "banana", "orange", "pineapple", "grape", "papaya"]
>>> print(fruits[1:5:1])
['mango', 'banana', 'orange', 'pineapple']
>>> print(fruits[1:5:2])
['mango', 'orange']

A negative value for stride specifies that we want to extract items from the list in reverse order.

>>> fruits = ["apple", "mango", "banana", "orange", "pineapple", "grape", "papaya"]
>>> print(fruits[4:1:-1])
['pineapple', 'orange', 'banana']
>>> print(fruits[-1:-4:-1])
['papaya', 'grape', 'pineapple']
>>> print(fruits[-2:-6:-2])
['grape', 'orange']
>>> print(fruits[::-1])
['papaya', 'grape', 'pineapple', 'orange', 'banana', 'mango', 'apple']

9. List Methods

Lists support a number of methods to perform common operations. It is important to remember that lists are mutable in Python. Therefore, invoking any method on a list will affect the list itself and not a copy of the list. Some of the most commonly used Python list methods are listed below.

list.append()

It adds a specified item to the end of the list.

>>> fruits = ["apple", "mango", "banana", "orange"]
>>> print(fruits)
['apple', 'mango', 'banana', 'orange']
>>> fruits.append("pineapple")
>>> print(fruits)
['apple', 'mango', 'banana', 'orange', 'pineapple']

list.insert()

It inserts an item at a specified index number. The first argument is the index number at which the item needs to be inserted and the second argument is the item itself.

>>> fruits = ["apple", "mango", "banana", "pineapple"]
>>> print(fruits)
['apple', 'mango', 'banana', 'pineapple']
>>> fruits.insert(3, "orange")
>>> print(fruits)
['apple', 'mango', 'banana', 'orange', 'pineapple']

list.remove()

It removes the first item from the list whose value is equal to the specified value.

>>> fruits = ["apple", "banana", "mango", "banana", "pineapple"]
>>> print(fruits)
['apple', 'banana', 'mango', 'banana', 'pineapple']
>>> fruits.remove("banana")
>>> print(fruits)
['apple', 'mango', 'banana', 'pineapple']

Trying to remove an item which is not present in the list results in an error.

>>> fruits = ["apple", "mango", "banana", "pineapple"]
>>> print(fruits)
['apple', 'mango', 'banana', 'pineapple']
>>> fruits.remove("grape")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list

list.pop()

It removes the item at the specified index number in the list and returns it. If no index number is specified, it removes and returns the last item in the list.

>>> fruits = ["apple", "mango", "banana", "orange", "pineapple", "grape", "papaya"]
>>> print(fruits)
['apple', 'mango', 'banana', 'orange', 'pineapple', 'grape', 'papaya']
>>> print(fruits.pop(2))
banana
>>> print(fruits)
['apple', 'mango', 'orange', 'pineapple', 'grape', 'papaya']
>>> print(fruits.pop())
papaya
>>> print(fruits)
['apple', 'mango', 'orange', 'pineapple', 'grape']

list.index()

It returns the index of the first item in the list whose value is equal to the specified value.

>>> fruits = ["apple", "orange", "mango", "banana", "orange", "pineapple"]
>>> print(fruits)
['apple', 'orange', 'mango', 'banana', 'orange', 'pineapple']
>>> print(fruits.index("orange"))
1

It produces an error if there is no item in the list with the specified value.

>>> fruits = ["apple", "mango", "banana", "orange", "pineapple"]
>>> print(fruits)
['apple', 'mango', 'banana', 'orange', 'pineapple']
>>> print(fruits.index("papaya"))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'papaya' is not in list

list.count()

It returns the number of times the specified value exists in the list.

>>> fruits = ["apple", "orange", "mango", "banana", "orange", "pineapple"]
>>> print(fruits)
['apple', 'orange', 'mango', 'banana', 'orange', 'pineapple']
>>> print(fruits.count("orange"))
2
>>> print(fruits.count("papaya"))
0

list.sort()

It is used to sort the items in a list.

>>> fruits = ["apple", "mango", "banana", "orange", "pineapple"]
>>> print(fruits)
['apple', 'mango', 'banana', 'orange', 'pineapple']
>>> fruits.sort()
>>> print(fruits)
['apple', 'banana', 'mango', 'orange', 'pineapple']

list.reverse()

It reverses the order of items in a list.

>>> fruits = ["apple", "mango", "banana", "orange", "pineapple"]
>>> print(fruits)
['apple', 'mango', 'banana', 'orange', 'pineapple']
>>> fruits.reverse()
>>> print(fruits)
['pineapple', 'orange', 'banana', 'mango', 'apple']

list.clear()

It removes all the items from a list.

>>> fruits = ["apple", "mango", "banana", "orange", "pineapple"]
>>> print(fruits)
['apple', 'mango', 'banana', 'orange', 'pineapple']
>>> fruits.clear()
>>> print(fruits)
[]

list.copy()

It makes a copy of a list. It is helpful in situations when a list needs to be manipulated while still having the original list available to us unchanged.

>>> fruits = ["apple", "mango", "banana", "orange", "pineapple"]
>>> print(fruits)
['apple', 'mango', 'banana', 'orange', '']
>>> new_fruits = fruits.copy()
>>> print(new_fruits)
['apple', 'mango', 'banana', 'orange', 'pineapple']

list.extend()

It is used to combine lists and takes in a second list as its argument.

>>> fruits1 = ["apple", "mango", "banana", "orange"]
>>> print(fruits1)
['apple', 'mango', 'banana', 'orange']
>>> fruits2 = ["pineapple", "papaya"]
>>> print(fruits2)
['pineapple', 'papaya']
>>> fruits1.extend(fruits2)
>>> print(fruits1)
['apple', 'mango', 'banana', 'orange', 'pineapple', 'papaya']
>>> print(fruits2)
['pineapple', 'papaya']
Lists in Python
5 (100%) 6 vote[s]