Working with lists and dictionaries in Python opens up a world of possibilities for data organization and manipulation. Imagine having a virtual toolbox where you can effortlessly store, retrieve, and modify data as needed—lists are like flexible containers for sequences of items, while dictionaries offer a powerful way to manage key-value pairs, allowing for quick access and updates. Whether you’re handling a collection of cities, tracking sales information, or navigating complex data structures, mastering these fundamental concepts will elevate your programming skills and enable you to tackle real-world challenges with confidence and creativity. Let’s dive into the exciting features and functionalities that lists and dictionaries have to offer!
For Beginners, free Python tutorials and libraries like numpy and pandas, you can refer to Introduction to Python.
This article was published as a part of the Data Science Blogathon.
Lists are just like arrays. Python lists are mutable data types in Python. A list refers to the collection of index value pair-like arrays in C/C++/Java. Lists is a 0-based index datatype, meaning the index of the first element starts at 0. Lists are used to store multiple items in a single variable. These are one of the 4 data types present in Python, i.e., Lists, Dictionaries, Tuples & Sets. A list is created by placing elements in [ ] separated by commas ‘, ‘. We can use them to store more complex data structures other than integers, strings, or floats. A list of dictionaries is a great example.
If there is a concept that is easier and more common than accessing elements in a list in Python, I still have not come across it. Through the use of indexing and slicing you can get, set or fetch portions of the list as you work with data since it is so flexible. It has both post-positive and pre-negative indexing system whereby anyone can begin from the beginning or the end of the list.
In Python, the list indices begin with 0 implying that the first element of any list is located at its zeroth index, the second element in the list is at first index, … It is done with equal ease by typing the required index number in square brackets after the list name.
Python Code:
num_list=[10,20,30,40,50,60,70,80,90]
city_list=['Agra','Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
print(city_list[2])
print(num_list[2])
Output:
Ahmedabad
30
Python also supports negative indexing, where -1
refers to the last element of the list, -2
refers to the second last element, and so on. This feature is particularly useful when you want to access elements from the end of the list.
print(city_list[-1])
Output:
Coimbatore
Note: If you try to access an index that is out of range, Python will raise an IndexError
. So, make sure the index you’re trying to access falls within the valid range of the list.
In Python, indexing is a powerful way to access and manipulate elements within a list. It allows you to retrieve a single element or a range of elements using indices. The ability to specify a range or slice of the list is extremely useful in various data manipulation tasks, enabling you to handle different portions of your list efficiently.
Python allows you to extract a sublist from an existing list using slicing. You define a range of indices, and Python will return the elements between those indices. The syntax for slicing is list[start:stop]
, where start
is the index of the first element you want to include, and stop
is the index where slicing ends (excluding the element at this position).
print(city_list[2:5])
Output:
['Ahmedabad', 'Surat', 'Lucknow']
When slicing, if you omit the start
index, Python will start from the beginning of the list. Similarly, omitting the stop
index will include all elements from the start index to the end of the list.
# Slicing from the start to the 3rd index
print(city_list[:3])
# Slicing from the 2nd index to the end
print(city_list[2:])
Output:
['Agra', 'Chennai', 'Ahmedabad']
['Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
Python’s index()
function allows you to find the index value of a specific item in a list, provided the item exists. You can also specify an optional range (start
, end
) within which Python should search for the item.
print(city_list.index('Chennai',0,3))
Output:
1
In Python you will find many types of operators that can be used with lists, including concatenation and repetition as well as comparisons. These operators are important to successfully manipulate list data type since they can boost your coding performance and option.
+
OperatorWithout any doubt one of the most frequently used operation which you will probably deal with when working with list is concatenation and in this case you will be glad to know that you can perform this operation using the + operator. This basic and helpful function also helps to combine multiple lists into one united collection and add the elements of one list to another without intervening between them. Just as you can tentatively compile a shopping list and your friend’s, you can instantly bring into being a new list containing what you need! For example:
num_city_list= num_list+ city_list
print(num_city_list)
Output:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 'Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
*
OperatorThe * operator aids in repetition of the contents of a list say N times to the list with simplycopying the contents. This applies where one wishes to repeat the same sequence of operations of the automated program or replicate other patterns.
new_citylist= city_list*2
print(new_citylist)
Output:
['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore', 'Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
In Python the comparison of two lists can be done using relational operators like ==,!=, <, >, <= and >=. These comparisons are done one feature at a time, beginning with the first feature of one list and the first feature of the other list. If first elements are equal Python try to compare the second elements and so on accordingly.
==
operator checks if two lists have the same elements in the same order.!=
operator checks if two lists are not the same.list1 = [10, 20, 30]
list2 = [10, 20, 30]
list3 = [30, 20, 10]
print(list1 == list2) # True
print(list1 != list3) # True
in
OperatorThe in
operator checks whether a specific element exists within a list, returning True
if the element is present and False
otherwise. This operator is often used to check membership in a list or search for values.
print('Ahmedabad' in city_list) # True
print(100 in num_list) # False
+=
and *=
OperatorsPython also supports the +=
and *=
operators for in-place modification of lists. The +=
operator appends the elements of another list to the existing list, and the *=
operator repeats the list elements in place.
num_list += [100, 110]
print(num_list) # [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110]
city_list *= 2
print(city_list) # ['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore', 'Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore'
Nested list is a list that is made up of one or more other list within it. It gives an opportunity to store any kind of more complex data arrangements like matrices, tables or hierarchical structures, and in each element of such structure is a list. When it comes to operating on the data, working with nested lists makes you have the ability to easily manage multi-dimensional data.
In the example below, list_nest
contains two elements, where each element is a list. The first nested list holds integers, and the second one contains strings:
list_nest=[[10,20,30],['a','b','c']]
list_nest
Output:
[[10, 20, 30], ['a', 'b', 'c']]
To access elements within a nested list, you need to use double indexing: the first index selects the sublist, and the second index picks an item from that sublist. This process allows you to navigate through the hierarchy of lists.
The elements of a nested list can be accessed as shown below:
print(list_nest[1][2])
Output:
c
Just like simple lists, elements within a nested list can also be modified using indexing. You can target specific items within the sublists and reassign their values.
list_nest[0][1] = 25
print(list_nest)
Output:
[[10, 25, 30], ['a', 'b', 'c']]
You can also append new lists to an existing nested list or add elements to the sublists themselves.
list_nest.append([40, 50, 60])
print(list_nest)
Output:
[[10, 25, 30], ['a', 'b', 'c'], [40, 50, 60]]
Python makes it easy to iterate through nested lists using loops, which is particularly useful when working with matrices or complex datasets. You can loop through both the parent list and the nested lists inside.
for sublist in list_nest:
for item in sublist:
print(item, end=" ")
Output:
10 25 30 a b c 40 50 60
Static means that an object cannot be altered once it has been defined; whereas lists are arbitrary, which means that elements may be altered even after creation. Python offers ways on how to manipulate lists for example add elements, add list to another list, add / insert elements at particular positions, replace list, remove elements and delete list. Explored in detail below are each of these techniques:
The append() method is used to add element to the list at the end of the list. This one alters the original list and is applied if the user must add only one item at a time.
city_list=['Agra','Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
city_list.append('Bangalore')
print(city_list)
Output:
['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore', 'Bangalore']
In the case where you want to append a number of elements to a list at one time then you can use the extend() method. Unlike the append () which takes only one element adds it to the list while the extend () takes a parameter that is iterable like a list and adds each element in the parameter to the list.
num_list = [10, 20, 30, 40, 50, 60, 70, 80, 90]
num_list.extend([100, 110, 120, 130, 140, 150])
print(num_list)
Output:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150]
To update a specific element in a list, you can assign a new value to the desired index. This method replaces the element at the specified position with a new one.
num_list[7]= 200
print(num_list)
Output:
[10, 20, 30, 40, 50, 60, 70, 200, 90, 100, 110, 120, 130, 140, 150]
In the present example inserting an item in the list at a given position is done with the help of insert() method. It takes two arguments: The indices and value as which are associated with the insert method are the index where it will insert the element and the value to be inserted.
city_list=['Agra','Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
city_list.insert(4,'Vadodara')
print(city_list)
Output:
['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Vadodara', 'Lucknow', 'Coimbatore']
You can delete elements from a list using the del
keyword. This can remove a single element by its index or a slice of elements by specifying a range of indexes.
city_list=['Agra','Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
del city_list[4]
print(city_list)
Output:
['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Coimbatore']
del city_list[4:6]
print(city_list)
Output:
['Agra', 'Chennai', 'Ahmedabad', 'Surat']
You can also delete the complete list using the below command:
del city_list
In order to delete the contents of a list but leave the variable intact, a list is assigned an empty list. This is important when you want to remake the list, but the list still serves as a good frame.
city_list = ['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
city_list = []
print(city_list)
Output:
[]
remove()
If you are aware of the value of the element which is to be removed but not its position, the remove() method is useful. It deletes the initial appearance of the value that is contained in its parameter.
city_list = ['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
city_list.remove('Ahmedabad')
print(city_list)
Output:
['Agra', 'Chennai', 'Surat', 'Lucknow', 'Coimbatore']
The pop()
method removes and returns an element from the list, either from the end (if no index is provided) or from a specified index.
city_list = ['Agra', 'Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
city_list.pop(3)
print(city_list)
Output:
['Agra', 'Chennai', 'Ahmedabad', 'Lucknow', 'Coimbatore']
Python offers several built-in methods to make list manipulation easier and more efficient. These methods allow you to perform various operations such as finding the length of a list, clearing its contents, reversing the order of elements, and sorting them. Let’s explore these methods in detail.
The len()
function is used to determine how many elements are present in a list. This method is very useful when you need to know the size of a list, especially in loops and conditions.
city_list=['Agra','Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
print(len(city_list))
Output:
6
The clear()
method is used to remove all elements from a list, effectively making it an empty list. It is a useful method when you want to reset a list without deleting the variable itself.
num_list = [1, 2, 2, 2, 3, 4, 5, 6, 6, 7, 6, 7]
num_list.clear()
print(num_list)
Output:
[]
The reverse()
method reverses the elements of a list in place, meaning it directly modifies the original list. This can be useful when the order of elements needs to be inverted.
city_list=['Agra','Chennai', 'Ahmedabad', 'Surat', 'Lucknow', 'Coimbatore']
city_list.reverse()
print(city_list)
Output:
['Coimbatore', 'Lucknow', 'Surat', 'Ahmedabad', 'Chennai', 'Agra']
The sort()
method sorts the elements of a list in ascending order by default. You can also pass the reverse=True
argument to sort the list in descending order. This method sorts elements in place, meaning it modifies the original list.
num_list=[1,2,2,2,3,4,5,6,6,7,6,7]
num_list.sort(reverse=True)
print(num_list)
Output:
[7, 7, 6, 6, 6, 5, 4, 3, 2, 2, 2, 1]
Dictionaries are mutable data types, unordered in nature, meaning they can be updated after they are created. Key and value pairs, and the keys must be unique. You can get a list of keys by calling a dictionary instance’s keys method. Syntactically they are written in a key, value pair format inside curly braces/curly brackets. We can update and delete the elements of the list of dictionaries. Dictionaries are implemented using hash tables.
{Key1:Value1,Key2:Value2,Key3:Value3,Key4:Value4}
Keys are always unique, and there cannot be any duplicates. There is no index in the dictionary, meaning they are not ordered. The key is the default iterator and is used to retrieve the value.
In Python, a dictionary is a collection of key-value pairs, allowing for efficient data retrieval and storage. Dictionaries can be created in several ways, each serving different needs. Here are four primary methods to create dictionaries in Python.
An empty dictionary can be created using curly braces {}
or the dict()
function. This can be useful when you want to initialize a dictionary and populate it later.
dict_emp={}
print(dict_emp)
Output:
{}
Dictionaries can have integer keys associated with their respective values. This is useful for storing data that requires numerical indexing.
dict_city={1: 'Ahmedabad', 2: 'Chennai', 3: 'Coimbatore',4:'Surat',5:'Agra'}
print(dict_city)
Output:
{1: 'Ahmedabad', 2: 'Chennai', 3: 'Coimbatore', 4: 'Surat', 5: 'Agra'}
String keys are commonly used in dictionaries, especially when representing named entities or attributes.
dict_travel={'Country1':'USA', 'Country2': 'India', 'Country3':'Japan', 'Country4':'UK', 'Country5': 'Australia'}
print(dict_travel)
Output:
{'Country1': 'USA', 'Country2': 'India', 'Country3': 'Japan', 'Country4': 'UK', 'Country5': 'Australia'}
Dictionaries can also contain a mix of different data types as keys and values, allowing for complex data structures.
mixed_dict= {'Country':'India', 1456:'Free','list':['city', 'road',12]}
print(mixed_dict)
Output:
{'Country': 'India', 1456: 'Free', 'list': ['city', 'road', 12]}
You can easily determine how many key-value pairs are in a dictionary using the len()
function. This can help in checking if a dictionary is empty or how many items it contains.
dict_salesid = {'Sale1': 200, 'Sale2': 150, 'Sale3': 300, 'Sale4': 250, 'Sale5': 400}
print(len(dict_salesid))
Output:
5
In Python, dictionaries are a versatile data structure that allows for efficient storage and retrieval of key-value pairs. Let’s explore various methods for accessing and manipulating dictionary elements.
First, let’s create two dictionaries to work with:
dict_salesid= {'SID1': Fiat
'SID2': Mercedes
'SID3': Maruti
'SID4': Volkswagen
'SID5': Kia}
dict_salesinfo= {'SID':Fiat,
'Sales': 20000
'LaunchDay':'Wed'
'Cost': 500000}
You can access the value associated with a key using the dictionary’s indexing method. Here’s how to extract the car name based on the sales ID:
sales_id='SID2'
if sales_id in dict_salesid:
name= dict_salesid[sales_id]
print('Sales ID is {}, Sales name is {}'. format(sales_id,name))
else:
print('Sales ID {} not found'.format(sales_id))
Output:
Sales ID is SID2, Sales name is Mercedes
You can also update existing keys or add new ones using the assignment operator. Here’s an example of modifying the LaunchDay
and Cost
in the dict_salesinfo
dictionary:
dict_salesinfo['LaunchDay']='Thurs'
dict_salesinfo['Cost']=6000000
LaunchDay= dict_salesinfo.get('LaunchDay')
Cost=dict_salesinfo.get('Cost')
print('Launchday is {}, Cost is {}'. format(LaunchDay,Cost))
Output:
Launchday is Thurs, Cost is 6000000
To view all the values in a dictionary, you can use the values()
method:
dict_values= dict_salesinfo.values()
print(dict_values)
Output:
dict_values(['Fiat', 20000, 'Wed', 500000])
The items()
function returns a view object displaying a list of a dictionary’s key-value tuple pairs:
dict_items = dict_salesinfo.items()
print(dict_items)
print(type(dict_items))
Output:
dict_items([('SID', 'Fiat'), ('Sales', 20000), ('LaunchDay', 'Wed'), ('Cost', 500000)])
<class 'dict_items'>
You can loop through the dictionary items using a for
loop, which allows you to process each key-value pair easily:
for key, value in dict_salesinfo.items():
print(key +"-"+str(value))
Output:
SID-Fiat
Sales-20000
LaunchDay-Wed
Cost-500000
A dictionary object contains key-value pairs, and the list must adhere to this format, or else it will throw an error.
sales_infolist=[['SID','Fiat'],['Sales','20000'],['LaunchDay','Wed'],['Cost','500000']]
print(type(sales_infolist))
sales_infolist_dict= dict(sales_infolist)
print(type(sales_infolist_dict))
Output:
<class 'list'>
<class 'dict'>
When working with dictionaries in Python, you may often need to create a copy of an existing dictionary to manipulate or reference data without altering the original. Understanding how to copy a dictionary ensures data integrity while providing the flexibility to make changes as needed.
dict_salesinfo_new= dict_salesinfo.copy()
print(dict_salesinfo_new)
Output:
{'SID': 'Fiat', 'Sales': 20000, 'LaunchDay': 'Wed', 'Cost': 500000}
Updating a Python dictionary allows you to modify existing key-value pairs or add new ones, making it a versatile tool for managing dynamic data. This functionality is essential for maintaining accurate and up-to-date information in your applications, enabling efficient data handling and retrieval.
dict_salesinfo= {'SID':'Fiat','Sales': 20000,'LaunchDay':'Wed','Cost': 500000}
dict_salesinfo.update({'Profit':'50000'})
print(dict_salesinfo)
Output:
{'SID': 'Fiat', 'Sales': 20000, 'LaunchDay': 'Wed', 'Cost': 500000, 'Profit': '50000'}
A dictionary object can be deleted entirely using the del
statement, which frees up memory by removing the entire dictionary and its contents.
del dict_salesinfo
Output:
The dictionary object is deleted
To delete a specific item from a dictionary, you can use the del
statement along with the key of the item you want to remove, as shown below:
del dict_salesinfo['SID']
print(dict_salesinfo)
Output:
{'Sales': 20000, 'LaunchDay': 'Wed', 'Cost': 500000}
Another way to delete a specific item is by using the pop function.
print(dict_salesinfo.pop('SID'))
Output:
Fiat
Looping through a Python dictionary allows you to access each key-value pair efficiently, making it easy to process or manipulate data. This technique is essential for tasks such as data analysis, reporting, or any situation where you need to examine or modify the contents of a dictionary.
dict_keys= dict_salesinfo.keys()
print(dict_keys)
print(type(dict_keys))
Output:
dict_keys(['SID', 'Sales', 'LaunchDay', 'Cost'])
<class 'dict_keys'>
for var in dict_keys:
print(var + ":" + str(dict_salesinfo[var]))
Output:
SID:Fiat
Sales:20000
LaunchDay:Wed
Cost:500000
In Python, a list is a class of data structures that can store one or more objects or values. A list can store multiple items in one variable and be created using square brackets. Dictionaries are used to store data values in key:value pairs. A dictionary is an ordered, changeable collection, and does not allow duplicates. Elements of the dictionary are accessed through the keys.
append()
, insert()
, and extend()
.items()
, keys()
, and values()
simplify working with key-value pairs.A. The main difference is we can access items in a python dictionary and dictionary values via keys and not by their position. A list is an ordered sequence of objects, whereas dictionaries are unordered sets.
A. We can use a list and a dictionary depending on the problem statement. Lists are used to store data in an ordered and sequential pattern. In comparison, a dictionary is used to store large amounts of data for easy and quick access. A list is ordered and mutable, whereas dictionaries are unordered and mutable.
A. We can store data in multiple ways, like Lists, Tuples, and dictionaries.
The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.
Great insights on using lists and dictionaries in Python! I particularly liked the examples you provided; they really helped clarify the concepts. Looking forward to more posts like this!
Great post! The examples you provided for manipulating lists and dictionaries in Python were really clear and helpful. I especially appreciated the tips on nested dictionaries—those are super useful for my current project! Looking forward to more articles like this.
Great post! I love how you broke down the differences between lists and dictionaries in Python. The examples were super helpful, especially the one about using dictionaries for faster lookups. Looking forward to trying out some of these techniques in my own projects!