Python Lists

This is a detailed tutorial on the Python List. Learn to create lists & perform different operations on them using various list methods with examples.

A list is a collection-type object in python. It’s a built-in data type in Python comparable to the commonly known arrays in most of the other popular programming languages. There are a total of four types of built-in data types in python to create a collection of items or elements. These are List, Tuple, Set, and Dictionary. Each of these has its own different properties. The list is a collection of items and the major properties of a Python List that differentiate it from the other collection objects are:

  • It is ordered. The user can define the items in the desired order and the list holds the items in that order.
  • It is changeable. Items can be altered. New items can be added, existing items can be removed, or can be modified with new items at any time.
  • Duplicate Items are allowed. A list may contain multiple occurrences of the same item.

So, in case, you want to choose a collection object in Python and you want these properties, you can choose a Python List. It is also one of the most commonly used data types in Python.

Creating a List

Creating a new List is super easy. A list is enclosed within square brackets [] and items are separated by commas , and are written inside these square brackets.

A list may hold items of any data type. The list items may or may not have the same data type. In other words, a list may contain items that may belong to only integers, only strings or even some belong to an integer, some to strings, and some to any other data type.

The following code illustrates the creation of different types of Python Lists.

#An Empty List
empty_list = []

#A List of Integers
integers_list = [1,2,3,4,5]

#A List of String Items
names = ["Gurmeet","WTMatter.com","Python","Tutorial"]

#A List of Mixed items belonging to different data types
mixed = ["Hello", 5.87, True, 10, 'a']

In the above example, the variable empty_list represents an empty list. The list integers_list only contains integer numbers and similarly, the list names only contains items belonging to the String datatype. And then there’s a list named mixed that contains items that belong to different data types such as String, Float, Boolean, and Integer.

A list may also contain another list and other collection objects as its elements or items. List elements inside another List to create a Nested List.

nested_list = [1, ["a", "b", "c"], [10, 12, 15, 19, 25], "Hello"]

Accessing List Items using Indexing

Before you can access the individual items of a list, you need to know the concept of Indexing. A list stores the list elements by indexes. These indexes are basically the positions of the items in the list defined by integer numbers.

The index in a Python List starts from 0. The first element of the list is always at index 0. The second element of the list is at index 1, the third one at index 2 and so on, this series continues.

To access the List items using these indexes, you have to use the square brackets notation containing the index of the item that you want to access. The following code demonstrates how you can do so.

#A Python List
arr = ["Hello","Hi","How","Are","You","?"]

#Accessing the elements using indexing
first_item = arr[0]
second_item = arr[1]
third_item = arr[2]
fourth_item = arr[3]
fifth_item = arr[4]
sixth_item = arr[5]

#Printing the elements
print("Item No. 1:",first_item)
print("Item No. 2:",second_item)
print("Item No. 3:",third_item)
print("Item No. 4:",fourth_item)
print("Item No. 5:",fifth_item)
print("Item No. 6:",sixth_item)

This code will give the following output.

Item No. 1: Hello
Item No. 2: Hi
Item No. 3: How
Item No. 4: Are
Item No. 5: You
Item No. 6: ?

Negative Indexing

Sometimes, there might be a requirement to access the last element of the list or the second last element. In that case, what will you do?

Will you do something like the following code?

numbers = [10, 12, 15, 19, 23, 45, 55, 89, 95, 105, 125]
list_length = len(numbers)
last_item = numbers[list_length-1]
second_last_item = numbers[list_length-2]
print(last_item, second_last_item)

Output.

125 105

To find out the last item of the item, first, the total number of items in the list will be calculated using the Python Built-in function len() and then you can subtract 1 from it, to find out the index of the last list element and similarly, you can subtract 2 to find out the index of the second last element to further access the items using the indexing method.

But that’s not the appropriate method. There’s an even easy way to access the items of a list, keeping in mind the reference of the index starts from the end of the list. This concept is called negative indexing.

Negative Indexing of a List starts from the right-hand side or from the end of the list from -1. In other words, the index of the last item in the list is always -1, the index of the second-last item is -2 and so on this continues up to the first item in the list.

The following example illustrates the same example as above but this time we’re making use of the negative indexing to access the last and second last list items.

numbers = [10, 12, 15, 19, 23, 45, 55, 89, 95, 105, 125]
last_item = numbers[-1]
second_last_item = numbers[-2]
print(last_item, second_last_item)

Output.

125 105

Python List Slicing

Slicing is a great concept in Python to get a range of items from a given Python List. To access a particular range of items from a list, the slicing operator : (colon) is used along with the item indexes.

The following example illustrates how you can do the slicing of the list to get your desired range of list items.

#A List with 10 items
#Indexes (0-9)
abc = ['a','b','c','d','e','f','g','h','i','j']

#Sublist from 5th to 8th item
#or from index 4 to index 7
print(abc[4:8])

#Sublist from 1st to 4th item
#or from index 0 to index 3
print(abc[0:4])

#Copy of the Original List
#from start to end
print(abc[:])

#Items from index 3 to End
print(abc[3:])

#Sublist from 8th Last Item To 5th Last Element
#Items from index -8 To -5
print(abc[-8:-4])

#Items from index -3 to start
print(abc[:-3])

#Sublist of Last 2 Items
print(abc[-2:])

Changing List Items

You can easily change the items of a list by referring to the list items using indexing and then assigning new values using the = assignment operator.

#list of cities
cities = ["London", "Birmingham", "New York", "Tokyo", "Dubai"]
print("Initial Cities:", cities)

#changing the item at index 1
cities[1] = "Ludhiana"
print("Updated Cities:", cities)

#changing the items from index 2 to 4
cities[2:5] = ["New Delhi", "Chandigarh", "Mumbai"]

Output.

Initial Cities: ['London', 'Birmingham', 'New York', 'Tokyo', 'Dubai']
Updated Cities: ['London', 'Ludhiana', 'New York', 'Tokyo', 'Dubai']
Updated Cities: ['London', 'Ludhiana', 'New Delhi', 'Chandigarh', 'Mumbai']

Adding New List Items

New items can be added to any existing Python list using two methods, append() and extend(). The list.append() method can be used to add a single new element to a given list and the list.extend() method can be used to add elements from another collection object like another list, tuple, or set into a given list.

#list of vegetables
vegetables = ["Tomato", "Potato", "Capsicum", "Onion", "Cauliflower"]

print("Initial List of Vegetables:",vegetables)

#Adding a new item using append()
vegetables.append("Lady Finger")

print("Updated List of Vegetables:",vegetables)

#Adding Multiple items
vegetables.extend(["Radish", "Pea", "Ginger"])

print("Updated List of Vegetables:",vegetables)

Output.

Initial List of Vegetables: ['Tomato', 'Potato', 'Capsicum', 'Onion', 'Cauliflower']
Updated List of Vegetables: ['Tomato', 'Potato', 'Capsicum', 'Onion', 'Cauliflower', 'Lady Finger']
Updated List of Vegetables: ['Tomato', 'Potato', 'Capsicum', 'Onion', 'Cauliflower', 'Lady Finger', 'Radish', 'Pea', 'Ginger']

The Python List extend() method is often used to merge two lists into a single list. You can also use the + operator to merge two list items into a single list and can also use the * operator to repeat the list items any number of items. The following example illustrates this.

list1 = [1, 'A', "Hello"]

list2 = ["5", 'E', "Bye"]

#Merging list1 and list2 into list3
list3 = list1 + list2

print("List 3:", list3)

#Multiplying list1 items 3 times into list4
list4 = list1 * 3

print("List 4:", list4)

Output.

List 3: [1, 'A', 'Hello', '5', 'E', 'Bye']
List 4: [1, 'A', 'Hello', 1, 'A', 'Hello', 1, 'A', 'Hello']

The new item to be added has to be provided as the argument to the append() method, while the new items to be added, have to be provided as a tuple, set, or list as the argument to the extend() method.

So far, we have added new elements at the end of the list. We also have the option to insert a new item at a particular index in a given list.

To add a new item at a desired index of the list, you can make use of the list.insert() method. This method takes two arguments. The first one is the index at which you want to insert a new item and the second argument is the item itself that is meant to be added to the list.

#list of marks
marks = [15, 25, 35, 45, 55, 65]

print("Initial Marks List:", marks)

#inserting a new item at index 2
marks.insert(2, 28)

print("Updated Marks List:", marks)

Output.

#list of marks
marks = [15, 25, 35, 45, 55, 65]

print("Initial Marks List:", marks)

#inserting a new item at index 2
marks.insert(2, 28)

print("Updated Marks List:", marks)

You can also add multiple new items at desired indexes using the scope resolution operator as illustrated in the following example.

#list of marks
marks = [15, 25, 35, 45, 55, 65]

print("Initial Marks List:", marks)

#inserting new items
#starting from index 4

marks[4:4] = [46, 47.5, 50, 52.5]

print("Updated Marks List:", marks)

Output.

Initial Marks List: [15, 25, 35, 45, 55, 65]
Updated Marks List: [15, 25, 35, 45, 46, 47.5, 50, 52.5, 55, 65]

Deleting or Removing List Items

Python provides two different methods for adding elements into the list, one by using the index i.e. insert() & one by using the item(s) itself, append() or extend(). Similarly, you can also remove or delete items from a given list either by their indexes or by the item values itself.

The list.pop() method is used to remove any item from a given list by its index. The index of the item to removed has to be passed as the argument to this method. Again, you can use positive as well as negative indexing for this purpose. The default value of the index argument here is -1. In other words, if you won’t provide any argument to this method, then this method will remove the last element from the list by default.

Another method is list.remove(). This method removes the item passed as its argument from a given list. The following example illustrates the usage of both of these methods.

smartphones = ["what!","iphone","oneplus","oppo","vivo","samsung","abc","hello","yeh","wow!"]

#Removing the last item from the list
smartphones.pop()

print("Updated List: ", smartphones)

#Removing the item at index 2
smartphones.pop(2)

print("Updated List: ", smartphones)

#Removing the third last item
smartphones.pop(-3)

print("Updated List: ", smartphones)

#Removing the item "yeh"
smartphones.remove("yeh")

print("Updated List: ", smartphones)

Output.

Updated List:  ['what!', 'iphone', 'oneplus', 'oppo', 'vivo', 'samsung', 'abc', 'hello', 'yeh']
Updated List:  ['what!', 'iphone', 'oppo', 'vivo', 'samsung', 'abc', 'hello', 'yeh']
Updated List:  ['what!', 'iphone', 'oppo', 'vivo', 'samsung', 'hello', 'yeh']
Updated List:  ['what!', 'iphone', 'oppo', 'vivo', 'samsung', 'hello']

You can also use the del keyword to delete one or more list items.

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

#deleting the item at index 4
del numbers[4]

print(numbers)

#deleting the items from index 5 to 8
del numbers[5:9]

print(numbers)

#making the list empty
del numbers[:]

print(numbers)

#deleting the list itself
del numbers

print(numbers)
[0, 1, 2, 3, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 5]
[]
Traceback (most recent call last):
  File "<stdin>", line 21, in <module>
    print(numbers)
NameError: name 'numbers' is not defined

There’s even one more method to make a list empty by clearing all of its items. The method name itself is clear().

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

#clearing all of the list items
numbers.clear()

print(numbers)

Output.

[]

Sorting a List

A Python list can be sorted in either Ascending/Descending or Custom order. The list.sort() method is used to sort a list and it takes two arguments. The first one is key and the second one is reverse. The reverse argument is a boolean type argument and is set to False by default. If the reverse argument is False, this method sorts the list element in Ascending Order and if it is True, this method sorts the list elements in Descending order.

The following example illustrates the sorting of a list.

#list of random numbers
randomNumbers = [11, 5, 9, 13, 25, 2, 5]

print("Random Order:", randomNumbers)

#sorting in Ascending Order
randomNumbers.sort()

print("Ascending Order:", randomNumbers)

#sorting in Descending Order
randomNumbers.sort(reverse = True)

print("Descending Order:", randomNumbers)

#list of names
names = ["bbbbb", "bbb", "bbbbbbb" , "b", "bb"]

#sorting according to length of the items
names.sort(key=len)

print("Small To Large (Length) Order:", names)

#sorting according to length of the items, Reverse Order
names.sort(key=len, reverse = True)

print("Large To Small (Length) Order:", names)
Random Order: [11, 5, 9, 13, 25, 2, 5]
Ascending Order: [2, 5, 5, 9, 11, 13, 25]
Descending Order: [25, 13, 11, 9, 5, 5, 2]
Small To Large (Length) Order: ['b', 'bb', 'bbb', 'bbbbb', 'bbbbbbb']
Large To Small (Length) Order: ['bbbbbbb', 'bbbbb', 'bbb', 'bb', 'b']

Python List Methods

There are several methods that you can apply on Python List objects to perform a number of actions on the list items. These methods are written below and each of these is linked with their detailed tutorial articles. Each of these tutorials includes a proper explanation of the working and usage of each of these methods with the help of illustrative examples.

Python List append()

It adds a single item at the end of a given list.


Python List clear()

It removes all the items from a given list and makes it empty.


Python List copy()

It returns a copy of the given list.


Python List count()

It returns the number of occurrences of a particular item in the list.


Python List extend()

It appends all of the items from another list to a given list.


Python List index()

It returns the index of the first occurrence of a particular item in the list.


Python List insert()

It is used to insert a particular item at a given index in the list.


Python List pop()

It is used to remove a particular element from the list by its index.


Python List remove()

It is used to remove a particular element from the list by the item itself.


Python List reverse()

It reverses the order of the items in the list.


Python List sort()

It is used to arrange the order of the items in either Ascending or Descending or in a custom order.


The following example illustrates the basic usage of the index(), count() and copy() methods.

#list with duplicate items
list1 = ["A","B","C","D","A","F","E","D","Y","D"]

#counting the occurrences of "A"
count = list1.count("A")

print("A comes", count, "times in the list.")

#finding the index of the first "D" item
D_firstOccurrenceIndex = list1.index("D")

print("D occurred first at index", D_firstOccurrenceIndex)

#Reversing the List order
list1.reverse()

print("Reversed List:", list1)

#list1 & list2 refer to the same list with the same items.
#list1 & list2 points to the same memory address
list2 = list1

#list2 is now a separate list with the same items
#list2 and list1 now has separate memory addresses
list2 = list1.copy()

print("New list2:", list2)

Output.

A comes 2 times in the list.
D occured first at index 3
Reversed List: ['D', 'Y', 'D', 'E', 'F', 'A', 'D', 'C', 'B', 'A']
New list2: ['D', 'Y', 'D', 'E', 'F', 'A', 'D', 'C', 'B', 'A']

Loop Through Python List

You can make use of the For Loops or While Loop to iterate through a list. In the following example, we’re looping through a list so as to print the string length of individual list items.

names = ["Dolly", "Gurmeet", "Pinki", "Ludhiana", "Nagpur", "Indian Ocean"]

#Loop through names
for name in names:
print("Length of",name,"is",len(name))

#Another Way
#Not Recommended
for i in range(len(names)):
print("Index",i,":",names[i])

Output.

names = ["Dolly", "Gurmeet", "Pinki", "Ludhiana", "Nagpur", "Indian Ocean"]

#Loop through names
for name in names:
    print("Length of",name,"is",len(name))
    
#Another Way
#Not Recommended
for i in range(len(names)):
    print("Index",i,":",names[i])

Check if an item exists in the list or not

You can simply use the membership operators in & not in to check if a particular item is present in a given Python List or not. This way you’ll get a boolean value i.e. either True (if the item is present in the list) or False. (if it’s not)

names = ["Dolly", "Gurmeet", "Pinki", "Ludhiana", "Nagpur", "Indian Ocean"]

print("Pinki" in names)

print("Hello" not in names)

print("Nagpur" not in names)

print("Avi" in names)

Output.

True
True
False
False

List Comprehension

This is a great way to dynamically generate python lists. For example, let’s say I’ve to create a list containing the square of all the numbers from 1 to 10 as its items. Then in such a case, you can create a list as illustrated in the following code by making use of the concept of list comprehension.

#list comprehension to generate
#a list of squares from 1 to 10
squares = [x*x for x in range(1,11)]

print(squares)

Output.

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

You can also make use of the If statement in the list comprehension syntax. The proper syntax for it is given below.

generated_list = [expression(x) for x in existing_list if condition(x)]

The above syntax is equivalent to the following syntax.

generated_list = []
for x in existing_list:
    if condition(x):
        generated_list.append(expression(x))

The following code will create a list of all the integer numbers which are multiples of 17 and lie between 0 and 1000.

multiple_17 = [x for x in range(0, 1000) if x % 17 == 0]

print("Multiples of 17 between from 0 To 1000:",multiple_17)

Output.

Multiples of 17 between from 0 To 1000: [0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255, 272, 289, 306, 323, 340, 357, 374, 391, 408, 425, 442, 459, 476, 493, 510, 527, 544, 561, 578, 595, 612, 629, 646, 663, 680, 697, 714, 731, 748, 765, 782, 799, 816, 833, 850, 867, 884, 901, 918, 935, 952, 969, 986]

Leave a Reply

Your email address will not be published. Required fields are marked *