Day 4 — Mastering Python Lists: Your Ultimate Guide 📚
Index
- Introducing Lists and Working with Lists😎
- What is a List? 📋
- How to access elements in the lists? 🔍
- How items are stored in the list? 🧐
- How to use individual values from the lists? 💡
- How to Modify, Add, and Remove Elements in the Lists? 🛠️
- How to Organize the Lists? 📊
- How to avoid some common index errors when working with lists? ❌
- Conclusion 🎉
1. Introducing Lists and Working with Lists 😊
Today we will learn about Lists, an exciting topic that forms the foundation of versatile data handling in Python.
2. What is a List? 📋
A list is a collection of items in a particular order. We can make a list that includes the letters of the alphabet, the digits from 0 to 9, all the subjects we study, or all the names of your favourite cricketers. We can put anything we want in the list and these items do not need to be related in any way. Because a list usually contains more than one element, it’s a good idea to make the name of our list plural, such as follows: cricket_players
, letters
, or employees
Lists are embraced using square brackets []
, and elements inside are separated by commas. Dive into the world of lists with these simple examples:
We can also print these lists, and Python will print its representation on the console including the square brackets.
#List of Cricket Players
cricket_players = ['M. S. Dhoni', 'Virat Kohli', 'Yuvraj Singh', 'Sachin Tendulkar', 'Virender Sehwagh', 'Irfan Pathan']
#List of Bollywood Actors
actors = ['Irrfan Khan', 'Manoj Vajpai', 'Rajpal Yadav', 'Satish Kaushik', 'Pankaj Tripathi', 'Vijay Raj', 'Sanjay Mishra']
#List of Bollywood Entertainers
entertainers = ['Salman Khan', 'Shah Rukh Khan', 'Ranveer Singh', 'Deepika Padukone', 'Aishwarya Rai', 'Kareena Kapoor']
#List of years of droughts in India
drought_years = [1876, 1899, 1918, 1965, 2000]
#Bank Nifty daily open positions
banknifty_open_prices = [44231.45, 44496.20, 44479.05, 43993.25, 44002.00]
#List with different data types
miscs = [1, 'cat', 2, 'tesla', 856.9, 'DAGS', 'something@address.com']
print(cricket_players)
print(actors)
print(entertainers)
print(drought_years)
print(banknifty_open_prices)
print(miscs)
We can also create the empty lists in Python:
#Empty List
profits = []
print(profits)
3. How to access elements in the lists? 🔍
Lists are the ordered collection, so we can access any element in a list by telling Python the position, or index, of the item desired.
To access an element in the list, write the name of the list followed by the index of the item enclosed in square brackets:
cricket_players = ['M. S. Dhoni', 'Virat Kohli', 'Yuvraj Singh', 'Sachin Tendulkar', 'Virender Sehwagh', 'Irfan Pathan']
print(cricket_players[0])
When we ask for a single item from a list, Python returns just that element without square brackets:
We can use the string methods on any element in the lists.
cricket_players = ['M. S. Dhoni', 'Virat Kohli', 'Yuvraj Singh', 'Sachin Tendulkar', 'Virender Sehwagh', 'Irfan Pathan']
print(cricket_players[1].upper())
print(cricket_players[1].lower())
print(cricket_players[1].title())
Python also provides us with a special syntax for accessing the list element in a list. If we want to access the items from the list from end positions we can use the below syntax for the same:
cricket_players = ['M. S. Dhoni', 'Virat Kohli', 'Yuvraj Singh', 'Sachin Tendulkar', 'Virender Sehwagh', 'Irfan Pathan']
print(cricket_players[-1])
print(cricket_players[-2])
Here, -1 will return the last element from the list, -2 will return the second last element, and so on.
Note: We can print the multiple elements from the lists, which we will see in the slicing of lists section.
4. How items are stored in the list? 🧐
Like other programming languages, Python considers the first item in a list to be at position 0 and not at position 1. Subsequently, the second item will be at position 1, the third at 2, and so on. Using this counting system, we can get any element from the list by subtracting 1 from its position in the list.
cricket_players = ['M. S. Dhoni', 'Virat Kohli', 'Yuvraj Singh', 'Sachin Tendulkar', 'Virender Sehwagh', 'Irfan Pathan']
print(cricket_players[0])
print(cricket_players[4])
and similar to accessing the elements from the end, they can be accessed using -1, -2, -3, and so on based on their position from the very end.
5. How to use individual values from the lists? 💡
We can use the individual values from the lists just as we could use any other variables. Consider an element from the list as any other variable and we can perform all the methods on that element.
The below example showcases how we can use the f-strings with list elements:
miscs = [1, 'cat', 2, 'tesla', 856.9, 'DAGS', 'something@address.com']
print(f"{miscs[3].title()} is one of the biggest car manufacturing companies in the world.")
Here, we accessed the element from position 3 applied the title method on it, and used it in a f-string.
Whenever we are unsure about the position of a particular element in the list we can use its value to know the exact position of that element, let’s take a look at the below example for the same.
miscs = [1, 'cat', 2, 'tesla', 856.9, 'DAGS', 'something@address.com']
print(f"{miscs[3].title()} is one of the biggest car manufacturing companies in the world.")
Here as we were unsure about the index value for the element ‘tesla’, we first printed the index for the element and then used the title() method with its index value.
6. How to Modify, Add, and Remove Elements in the Lists? 🛠️
Most lists we will create will be dynamic, meaning we will have to add, update, and delete data whenever necessary. For example, if we have the list of Employees, we will have to keep altering it whenever a new employee joins the team, leaves the team, or needs to change his name, etc.
6.1. Modifying Elements in a list🔧
We can use similar syntax for modifying/updating an individual element in the list as we use for accessing the element, because even logically if we need to modify/update an element we will first have to access it and then modify it.
Let’s check the below example where we modify the value tesla and use the string method on it:
miscs = [1, 'cat', 2, 'teSLa', 856.9, 'DAGS', 'something@address.com']
print(miscs)
print(miscs[3])
miscs[3] = miscs[3].title()
print(miscs)
In the above example, we accessed the element at index 3, applied the title() method on it, and updated the original list.
6.2. Adding Elements in a List ➕
We might need to add new elements to the list for different reasons. Python gives us several ways to add new elements to our list:
6.2.1 Appending Elements to the List➕📥
The simplest way to add a new element to the list is to append an element at the end of the list. Whenever we append an item to a list, the new element is added to the very end of the list without affecting any other element in the list.
The append method makes it very easy to build lists dynamically.
bikes = ['Yamaha FZ', 'Bajaj Pulsar', 'Gixxer', 'Honda CB 350']
print(bikes)
bikes.append('Yamaha R15')
bikes.append('Helicat')
print(bikes)
6.2.2 Inserting Elements in a List:➕🎯
Unlike what append does to add a new element at the end of the list, what if we need to add a new element at a particular position/index we need? Note to worry Python has an insert method with which we can easily insert new elements at the position that we need.
bikes = ['Yamaha FZ', 'Bajaj Pulsar', 'Gixxer', 'Honda CB 350']
print(bikes)
bikes.insert(0, 'Helicat')
bikes.insert(1, 'Yamaha R15')
print(bikes)
bikes.insert(5, 'Ola S2')
print(bikes)
If we observe the output here, we will see that whenever we use the insert method, it will shift other values in the list one position to the right.
6.3. Removing the Elements from the lists🚫🗑️
Sometimes we also need to remove elements from the list, like if an employee leaves the company, or if the customer has been inactive for many months, etc. We can remove an item according to its position in the lists or according to its values.
6.3.1 Removing an item with Del statement❌
If we know the position/index of an element we need to remove, we can use the del()
statement:
bikes = ['Yamaha FZ', 'Bajaj Pulsar', 'Gixxer', 'Honda CB 350']
print(bikes)
print(bikes[1])
del(bikes[1])
print(bikes)
6.3.2 Removing item by Value💎
Sometimes we do not know the position of the value we want to delete, if we have millions of items in the list it will be a lot harder to know the exact index or the position of the value. In such cases, we can remove the element from the list by using its value:
To remove an element from the list using value Python uses theremove()
method.
bikes = ['Yamaha FZ', 'Bajaj Pulsar', 'Gixxer', 'Honda CB 350']
print(bikes)
print(bikes[1])
bikes.remove('Bajaj Pulsar')
print(bikes)
In addition to the del()
and remove()
methods Python also provides us with the pop()
method which we can use to remove elements from the list:
6.3.3 Removing an item using the pop()
method🍿
Sometimes we need to use the value of an item after we remove it from a list.
For example, we might need to remove employees from the testing team and add them to the development team.
The pop()
method removes the last item in a list, but it lets you work with that item after removing it. The term pop comes from thinking of a list as a stack of items and popping one item from the top of the stack. Here top of the stack means the last element of the list:
testers = ['Some Tester 1', 'Some Tester 2', 'Some Tester 3']
developers = ['Some Developer 1', 'Some Developer 2', 'Some Developer 3']
print(testers)
print(developers)
popped_tester = testers.pop()
print(popped_tester)
print(testers)
developers.append(popped_tester)
print(developers)
Here, we are popping the last tester and using it to append the developers list.
6.3.4 Removing an item using the pop() method from any position in a list🍿
We can use pop()
to remove an item from any position in a list by including the index of the item we want to remove in parenthesis:
testers = ['Some Tester 1', 'Some Tester 2', 'Some Tester 3']
developers = ['Some Developer 1', 'Some Developer 2', 'Some Developer 3']
print(testers)
print(developers)
popped_tester = testers.pop(0)
print(popped_tester)
print(testers)
developers.append(popped_tester)
print(developers)
Here, instead of popping the last element from the tester list, we are removing the element from the desired position.
Note: The remove()
method deletes the first occurrence of the value we specify. If there’s a possibility the value appears more than once in the list, we will need to use a loop to make sure all the occurrences of the values are removed.
7. How to Organize the Lists? 📊
Often, our lists will be created in an unpredictable order because we can’t always control the order in which the user provides the data. So sometimes we might need to order these lists.
Python provides several different ways to organize our lists which we can use based on our requirements:
7.1 Sorting a List permanently with the sort() method 🏢🧹
Python provides us with the sort()
method that makes it easy to sort a list. Imagine we have a list of cars, and we want to store these cars in alphabetical order. The sort()
method changes the order of the list permanently.
cars = ['Tiago', 'Tigor', 'Punch', 'Altroz']
print(cars)
cars.sort()
print(cars)
We can also sort this list in reverse alphabetical order by passing the argument reverse = True
to the sort()
method.
cars = ['Tiago', 'Tigor', 'Punch', 'Altroz']
print('Original List: \t', cars)
cars.sort(reverse=False)
print(f'Sorted List: \t {cars}')
cars.sort(reverse=True)
print(f'Reverse List:\t {cars}')
7.2 Sorting a list Temporarily with the sorted() function⏳🧹
To maintain the original order of a list but present it in a sorted order, we can use the sorted()
method.
The sorted()
method function lets us display our list in a particular order but doesn’t affect the actual order of the list.
cars = ['Tiago', 'Tigor', 'Punch', 'Altroz']
print(f"Original List: \t\t {cars}")
print(f"Temporary Sort: \t {sorted(cars)}")
print(f"Original After Temp Sort: {cars}")
We can also sort this list in reverse alphabetical order by passing the argument reverse = True
to the sorted(list_name, reverse = True)
method.
cars = ['Tiago', 'Tigor', 'Punch', 'Altroz']
print(f"Original List: \t\t {cars}")
print(f"Temporary Sort: \t {sorted(cars, reverse = False)}")
print(f"Temporary Reverse Sort: {sorted(cars, reverse = True)}")
print(f"Original After Temp Sort: {cars}")
Note: Sorting a list is a bit complicated when all the values are not in uppercase or lowercase. Let’s take a look at the below example:
cars = ['tiago', 'tigor', 'Punch', 'altroz']
print(cars)
cars.sort()
print(cars)
We can see here that Punch is displayed before the altroz.
7.3 Print a List in Reverse Order🔄📊
To reverse the original order of a list, we can use reverse()
method. Here the elements from the list are not sorted but are reversed.
reverse()
method doesn’t sort backward alphabetically; it simply reverses the order of the list, and it also changes the order of the list permanently:
cars = ['tiago', 'tigor', 'punch', 'altroz', 'thar']
print(f"Original Order: {cars}")
cars.reverse()
print(f"Reversed List: {cars}")
7.4 Finding the length of a list📏
We can quickly find the length of a list by using the len()
method. We can use the len()
method whenever we need to identify the number of elements in the list.
Python counts the item in a list starting with 1, not 0 (index).
cars = ['tiago', 'tigor', 'punch', 'altroz', 'thar']
print(len(cars))
print(f"Total Number of elements in Cars: {len(cars)}")
8. How to avoid some common index errors when working with lists? ❌
8.1 Avoiding Index Errors when working with lists:
There are some types of errors that are very common to see when we work with the list for the first time. Let’s say we have a list with three items, and we ask for the fourth:
numbers = [2, 5, 3, 4, 1]
print(numbers[5])
An index error means Python cannot find an item at the index we requested. If an index error occurs in our program, try adjusting the index we are asking.
9. Conclusion 🎉
In conclusion, mastering Python lists opens the door to dynamic data handling 😃. We’ve journeyed through accessing, modifying, and organizing elements. From 📋 to ➕, 🛠️ to 📊, you’re equipped to wrangle data like a pro. Keep coding and exploring — exciting Python adventures await! 🚀