Tuple, List, Dictionary
Tuple, List, Dictionary
In this article, you will learn how to use a tuple data structure in Python. Also,
learn how to create, access, and modify a tuple in Python and all other operations
we can perform on a tuple.
What is a Tuple
Tuples are ordered collections of heterogeneous data that are
unchangeable. Heterogeneous means tuple can store variables of all types.
• Ordered: Tuples are part of sequence data types, which means they hold
the order of the data insertion. It maintains the index value for each item.
• Unchangeable: Tuples are unchangeable, which means that we cannot add
or delete items to the tuple after creation.
• Heterogeneous: Tuples are a sequence of data of different data types
(like integer, float, list, string, etc;) and can be accessed through indexing
and slicing.
• Contains Duplicates: Tuples can contain duplicates, which means they can
have items with the same value.
Python tuples
Creating a Tuple
We can create a tuple using the two ways
Example
A tuple can have items of different data type integer, float, list, string, etc;
Run
As we can see in the above output, the different items are added in the tuple like
integer, string, and list.
A single item tuple is created by enclosing one item inside parentheses followed
by a comma. If the tuple time is a string enclosed within parentheses and not
followed by a comma, Python treats it as a str type. Let us see this with an
example.
# without comma
single_tuple = ('Hello')
print(type(single_tuple))
# Output class 'str'
print(single_tuple)
# Output Hello
# with comma
single_tuple1 = ('Hello',)
# output class 'tuple'
print(type(single_tuple1))
# Output ('Hello',)
print(single_tuple1)
Run
As we can see in the above output the first time, we did not add a comma after
the “Hello”. So the variable type was class str, and the second time it was a
class tuple.
A tuple can also be created without using a tuple() constructor or enclosing the
items inside the parentheses. It is called the variable “Packing.”
Similarly, we can unpack the items by just assigning the tuple items to the same
number of variables. This process is called “Unpacking.”
print(type(tuple1))
# Output class 'tuple'
Run
As we can see in the above output, three tuple items are assigned to individual
variables i, j, k, respectively.
In case we assign fewer variables than the number of items in the tuple, we will
get the value error with the message too many values to unpack
Length of a Tuple
We can find the length of the tuple using the len() function. This will return the
number of items in the tuple.
Run
Iterating a Tuple
We can iterate a tuple using a for loop Let us see this with an example.
# create a tuple
sample_tuple = tuple((1, 2, 3, "Hello", [4, 8, 16]))
# iterate a tuple
for item in sample_tuple:
print(item)
Run
Output
Hello
[4, 8, 16]
As we can see in the above output we are printing each and every item in the
tuple using a loop.
Accessing items of a Tuple
Tuple can be accessed through indexing and slicing. This section will guide you
by accessing tuple using the following two ways
• Using indexing, we can access any item from a tuple using its index
number
• Using slicing, we can access a range of items from a tuple
Indexing
A tuple is an ordered sequence of items, which means they hold the order of the
data insertion. It maintains the index value for each item.
We can access an item of a tuple by using its index number inside the index
operator [] and this process is called “Indexing”.
Note:
• As tuples are ordered sequences of items, the index values start from 0 to
the tuple’s length.
• Whenever we try to access an item with an index more than the tuple’s
length, it will throw the 'Index Error'.
• Similarly, the index values are always integer. If we give any other type, then
it will throw Type Error.
In the above image, we can see that the index values start from zero and it goes
till the last item whose index value will be len(tuple) - 1 .
Run
Output
As seen in the above example, we print the tuple’s first four items with the
indexing.
Note: If we mention the index value greater than the length of a tuple then it will
throw an index error.
Run
Also, if you mention any index value other than integer then it will throw Type
Error.
Run
Negative Indexing
The index values can also be negative, with the last but the first items having the
index value as -1 and second last -2 and so on.
For example, We can access the last item of a tuple using tuple_name[-1].
Run
Slicing a tuple
We can even specify a range of items to be accessed from a tuple using the
technique called ‘Slicing.’ The operator used is ':'.
We can specify the start and end values for the range of items to be accessed
from the tuple. The output will be a tuple, and it includes the range of items
with the index values from the start till the end of the range. The end value item
will be excluded.
We should keep in mind that the index value always starts with a 0.
For easy understanding, we will be using an integer tuple with values from 0 to 9
similar to how an index value is assigned.
Run
As seen in the above output the values starting from 1 to 4 are printed. Here the
last value in the range 5 is excluded.
Note:
• If the start value is not mentioned while slicing a tuple, then the values in
the tuples start from the first item until the end item in the range. Again the
end item in the range will be excluded.
• Similarly, we can mention a slicing range without the end value. In that case,
the item with the index mentioned in the start value of the range till the end
of the tuple will be returned.
Example
Run
Similarly, we can slice tuple using negative indexing as well. The last but first item
will have the index -1.
Run
Here we can see that the items with the negative indexes starting from -1 till -4
are printed excluding -5.
Example
Run
As seen in the above output the index value of item 30 is printed.
We can mention the start and end values for the index() method so that our
search will be limited to those values.
Example
Run
As seen in the above output we have limited the search from the index position 4
to 6 as the number 60 is present in this range only. In case we mention any item
that is not present then it will throw a value error.
Run
We can check whether an item exists in a tuple by using the in operator. This will
return a boolean True if the item exists and False if it doesn’t.
tuple1 = (10, 20, 30, 40, 50, 60, 70, 80)
# checking whether item 50 exists in tuple
print(50 in tuple1)
# Output True
print(500 in tuple1)
# Output False
Run
As seen in the above output we can see that the item ’50’ exists in the tuple so
we got True and ‘500’ doesn’t and so we got False.
Also, because a tuple is immutable there are no built-in methods to add items to
the tuple.
Example
tuple1 = (0, 1, 2, 3, 4, 5)
tuple1[1] = 10
# Output TypeError: 'tuple' object does not support item assignment
Run
As a workaround solution, we can convert the tuple to a list, add items, and then
convert it back to a tuple. As tuples are ordered collection like lists the items
always get added in the end.
tuple1 = (0, 1, 2, 3, 4, 5)
Run
As we can see in the above output the item is added to the tuple in the end.
One thing to remember here, If one of the items is itself a mutable data type as a
list, then we can change its values in the case of a nested tuple.
For example, let’s assume you have the following tuple which has a list as its last
item and you wanted to modify the list items.
Let’s see how to modify the set item if it contains mutable types.
Example
Run
As tuples are immutable we cannot change the values of items in the tuple. Again
with the same workaround we can convert it into a list, make changes and
convert it back into a tuple.
tuple1 = (0, 1, 2, 3, 4, 5)
# converting tuple into a list
sample_list = list(tuple1)
# modify 2nd item
sample_list[1] = 10
Run
As we can see in the above output the last item has been updated from 3 to 11.
sampletup1 =(0,1,2,3,4,5,6,7,8,9,10)
del sampletup1
print(sampletup1)
Run
Output
----> 4 print(sampletup1)
NameError: name 'sampletup1' is not defined
As seen in the above output we are getting error when we try to access a deleted
tuple.
We can convert a tuple into a list and then remove any one item using
the remove() method. Then again we will convert it back into a tuple using
the tuple() constructor.
tuple1 = (0, 1, 2, 3, 4, 5)
Run
As seen in the above output item 3 has been removed from the tuple.
The count() method accepts any value as a parameter and returns the number of
times a particular value appears in a tuple.
Example
count = tuple1.count(600)
print(count)
# Output 0
Run
Copying a tuple
We can create a copy of a tuple using the assignment operator '=' . This
operation will create only a reference copy and not a deep copy because tuples
are immutable.
tuple1 = (0, 1, 2, 3, 4, 5)
# copy tuple
tuple2 = tuple1
print(tuple2)
# Output (0, 1, 2, 3, 4, 5)
# changing tuple2
# converting it into a list
sample_list = list(tuple2)
sample_list.append(6)
Run
As we can see in the above output the tuple1 is not affected by the changes
made in tuple2.
We can add two tuples using the + operator. This is a very and straightforward
method and the resultant tuple will have items from both the tuples.
tuple1 = (1, 2, 3, 4, 5)
tuple2 = (3, 4, 5, 6, 7)
Run
As seen in the above output the resultant tuple has items from both the tuples
and the item 3, 4, 5 are repeated twice.
We can also use the Python built-in function sum to concatenate two tuples. But
the sum function of two iterables like tuples always needs to start with Empty
Tuple. Let us see this with an example.
tuple1 = (1, 2, 3, 4, 5)
tuple2 = (3, 4, 5, 6, 7)
Run
As we can see in the above output the sum function takes an Empty tuple as an
argument and it returns the items from both the tuples.
The chain() function is part of the itertools module in python. It makes an iterator,
which will return all the first iterable items (a tuple in our case), which will be
followed by the second iterable. We can pass any number of tuples to the chain()
function.
import itertools
tuple1 = (1, 2, 3, 4, 5)
tuple2 = (3, 4, 5, 6, 7)
# using itertools
tuple3 = tuple(item for item in itertools.chain(tuple1, tuple2))
print(tuple3)
# Output (1, 2, 3, 4, 5, 3, 4, 5, 6, 7)
Run
As seen in the above output we can concatenate any number of tuples using the
above method and it is more time-efficient than other methods.
Nested tuples
Nested tuples are tuples within a tuple i.e., when a tuple contains another tuple
as its member then it is called a nested tuple.
In order to retrieve the items of the inner tuple we need a nested for loop
Run
Output
P, y, t, h, o, n,
As the name suggests the max() function returns the maximum item in a tuple
and min() returns the minimum value in a tuple.
Run
Note: We can’t find the max() and min() for a heterogeneous tuple (mixed types
of items). It will throw Type Error
Run
all()
In the case of all() function, the return value will be true only when all the values
inside are true. Let us see the different item values and the return values.
Run
any()
The any() method will return true if there is at least one true value. In the case of
the empty tuple, it will return false. Let us see the same possible combination of
values for any() function in a tuple and its return values.
Similarly, let’s see each one of the above scenarios with a small example.
Run
t1 = (10, 20, 30, 40, 50) and t2 = (60, 70, 80, 60)
Operation Description
t1 + t2 Concatenate the tuples t1 and t2. Creates a new tuple containing the items from t1 and t2.
Tuple slicing. Get the items from index i up to index j (excluding j) as a tuple. An
t1[i:j]
example t1[0:2] is (10, 20)
Tuple slicing with step. Return a tuple with the items from index i up to index j taking every
t1[i:j:k]
k-th item. An example t1[0:4:2] is (10, 30)
t2.count(60) Returns the number of times a particular item (60) appears in a tuple. Answer is 2
t1.index(40, 2, Returns the index number of a particular item(30) in a tuple. But search only from index
5) number 2 to 5.
Dictionaries in Python
Dictionaries are ordered collections of unique values stored in (Key-Value)
pairs.
In Python version 3.7 and onwards, dictionaries are ordered. In Python 3.6 and
earlier, dictionaries are unordered.
For example, consider the Phone lookup, where it is very easy and fast to find the
phone number(value) when we know the name(Key) associated with it.
Characteristics of dictionaries
• Unordered (In Python 3.6 and lower version): The items in dictionaries are
stored without any index value, which is typically a range of numbers. They
are stored as Key-Value pairs, and the keys are their index, which will not be
in any sequence.
• Ordered (In Python 3.7 and higher version): dictionaries are ordered, which
means that the items have a defined order, and that order will not change. A
simple Hash Table consists of key-value pair arranged in pseudo-random
order based on the calculations from Hash Function.
• Unique: As mentioned above, each value has a Key; the Keys in Dictionaries
should be unique. If we store any value with a Key that already exists, then
the most recent value will replace the old value.
• Mutable: The dictionaries are changeable collections, which implies that we
can add or remove items after the creation.
Table of contents
Creating a dictionary
There are following three ways to create a dictionary.
• Using curly brackets: The dictionaries are created by enclosing the comma-
separated Key: Value pairs inside the {} curly brackets. The colon ‘:‘ is used
to separate the key and value in a pair.
• Using dict() constructor: Create a dictionary by passing the comma-
separated key: value pairs inside the dict().
• Using sequence having each item as a pair (key-value)
Let’s see each one of them with an example.
Example:
Run
Empty Dictionary
When we create a dictionary without any elements inside the curly brackets then
it will be an empty dictionary.
emptydict = {}
print(type(emptydict))
# Output class 'dict'
Run
Note:
• A dictionary value can be of any type, and duplicates are allowed in that.
• Keys in the dictionary must be unique and of immutable types like string,
numbers, or tuples.
1. Retrieve value using the key name inside the [] square brackets
2. Retrieve value by passing key name as a parameter to the get() method of a
dictionary.
Example
Run
As we can see in the output, we retrieved the value ‘Jessa’ using key ‘name” and
value 1178 using its Key ‘telephone’.
Use the following dictionary methods to retrieve all key and values at once
Method Description
items() Returns all the items present in the dictionary. Each item will be inside a tuple as a key-value pair.
We can assign each method’s output to a separate variable and use that for
further computations if required.
Example
Run
Iterating a dictionary
We can iterate through a dictionary using a for-loop and access the individual
keys and their corresponding values. Let us see this with an example.
Run
Output
key : value
name : Jessa
country : USA
telephone : 1178
key : value
name Jessa
country USA
telephone 1178
Run
Example
Run
Note: We can also add more than one key using the update() method.
Example
Run
Using the setdefault() method default value can be assigned to a key in the
dictionary. In case the key doesn’t exist already, then the key will be inserted into
the dictionary, and the value becomes the default value, and None will be
inserted if a value is not mentioned.
In case the key exists, then it will return the value of a key.
Example
# Display dictionary
for key, value in person_details.items():
print(key, ':', value)
Run
Output
name : Jessa
country : USA
telephone : 1178
state : Texas
zip : None
Note: As seen in the above example the value of the setdefault() method has no
effect on the ‘country’ as the key already exists.
• Using key name: We can directly assign new values by using its key name.
The key name will be the existing one and we can mention the new value.
• Using update() method: We can use the update method by passing the
key-value pair to change the value. Here the key name will be the existing
one, and the value to be updated will be new.
Example
person = {"name": "Jessa", "country": "USA"}
Run
Method Description
Return and removes the item with the key and return its value. If the key is not found, it
pop(key[,d])
raises KeyError.
Return and removes the last inserted item from the dictionary. If the dictionary is empty, it
popitem()
raises KeyError.
del key The del keyword will delete the item with the key that is passed
clear() Removes all items from the dictionary. Empty the dictionary
del
Delete the entire dictionary
dict_name
Now, Let’s see how to delete items from a dictionary with an example.
Example
Run
In this method, we can just check whether our key is present in the list of keys
that will be returned from the keys() method.
Let’s check whether the ‘country’ key exists and prints its value if found.
person = {'name': 'Jessa', 'country': 'USA', 'telephone': 1178}
Run
In this method, the dictionary to be added will be passed as the argument to the
update() method and the updated dictionary will have items of both the
dictionaries.
Let’s see how to merge the second dictionary into the first dictionary
Example
Run
As seen in the above example the items of both the dictionaries have been
updated and the dict1 will have the items from both the dictionaries.
Using **kwargs to unpack
We can unpack any number of dictionary and add their contents to another
dictionary using **kwargs. In this way, we can add multiple length arguments to
one dictionary in a single statement.
Run
As seen in the above example the values of all the dictionaries have been merged
into one.
Note: One thing to note here is that if both the dictionaries have a common key
then the first dictionary value will be overridden with the second dictionary value.
Example
Run
As mentioned in the case of the same key in two dictionaries the latest one will
override the old one.
In the above example, both the dictionaries have the key ‘Emma’ So the value of
the second dictionary is used in the final merged dictionary dict1.
Copy a Dictionary
We can create a copy of a dictionary using the following two ways
Run
Note: When you set dict2 = dict1, you are making them refer to the same dict
object, so when you modify one of them, all references associated with that
object reflect the current state of the object. So don’t use the assignment
operator to copy the dictionary instead use the copy() method.
Example
dict1 = {'Jessa': 70, 'Emma': 55}
print(dict1)
# Output {'Jessa': 90, 'Emma': 55}
Run
Nested dictionary
Nested dictionaries are dictionaries that have one or more dictionaries as their
members. It is a collection of many dictionaries in one dictionary.
Example
# Display dictionary
print("person:", person)
Run
Output
City: Houston
Person details
name: Jessa
company: Google
Person Address
state: Texas
city : Houston
As we can see in the output we have added one dictionary inside another
dictionary.
In this example, we will create a separate dictionary for each student and in the
end, we will add each student to the ‘class_six’ dictionary. So each student is
nothing but a key in a ‘class_six’ dictionary.
In order to access the nested dictionary values, we have to pass the outer
dictionary key, followed by the individual dictionary key.
We can iterate through the individual member dictionaries using nested for-loop
with the outer loop for the outer dictionary and inner loop for retrieving the
members of the collection.
Example
Run
Output
Student 3 marks: 85
Class details
student1
name: Jessa
state: Texas
city: Houston
marks: 75
student2
name: Emma
state: Texas
city: Dallas
marks: 60
student3
name: Kelly
state: Texas
city: Austin
marks : 85
As seen in the above example, we are adding three individual dictionaries inside a
single dictionary.
Sort dictionary
The built-in method sorted() will sort the keys in the dictionary and returns a
sorted list. In case we want to sort the values we can first get the values using
the values() and then sort them.
Example
Run
As we can see in the above example the keys are sorted in the first function call
and in the second the values are sorted after the values() method call.
Dictionary comprehension
Dictionary comprehension is one way of creating the dictionary where the values
of the key values are generated in a for-loop and we can filter the items to be
added to the dictionary with an optional if condition. The general syntax is as
follows
# calculate the square of each even number from a list and store in dict
numbers = [1, 3, 5, 2, 8]
even_squares = {x: x ** 2 for x in numbers if x % 2 == 0}
print(even_squares)
Run
Here in this example, we can see that a dictionary is created with an input list (any
iterable can be given), the numbers from the list being the key and the value is
the square of a number.
We can even have two different iterables for the key and value and zip them
inside the for loop to create a dictionary.
In the above example, we are creating a telephone directory with separate tuples
for the key which is the name, and the telephone number which is the value. We
are zipping both the tuples together inside the for a loop.
As the name suggests the max() and min() functions will return the keys with
maximum and minimum values in a dictionary respectively. Only the keys are
considered here not their corresponding values.
dict = {1:'aaa',2:'bbb',3:'AAA'}
print('Maximum Key',max(dict)) # 3
print('Minimum Key',min(dict)) # 1
Run
As we can see max() and min() considered the keys to finding the maximum and
minimum values respectively.
all()
When the built-in function all() is used with the dictionary the return value will
be true in the case of all – true keys and false in case one of the keys is false.
#empty dictionary
dict3= {}
Run
Output
any()
any()function will return true if dictionary keys contain anyone false which could
be 0 or false. Let us see what any() method will return for the above cases.
#empty dictionary
dict3= {}
#all false
dict5 = {0:False}
Run
Output
As we can see this method returns true even if there is one true value and one
thing to note here is that it returns false for empty dictionary and all false
dictionary.
For example, consider the phone lookup where it is very easy and fast to find the
phone number (value) when we know the name (key) associated with it.
So to associate values with keys in a more optimized format and to retrieve them
efficiently using that key, later on, dictionaries could be used.
Also, try to solve the Python dictionary exercise and dictionary Quiz.
Operations Description
Returns a list of all the items in the dictionary with each key-value pair inside a
d1.items()
tuple.
max(d1) Returns the key with the maximum value in the dictionary d1
min(d1) Returns the key with the minimum value in the dictionary d1
Python Lists
Python list is an ordered sequence of items.
In this article you will learn the different methods of creating a list, adding,
modifying, and deleting elements in the list. Also, learn how to iterate the list and
access the elements in the list in detail. Nested Lists and List Comprehension are
also discussed in detail with examples.
Also See:
Python List
The following are the properties of a list.
• Mutable: The elements of the list can be modified. We can add or remove
items to the list after it has been created.
• Ordered: The items in the lists are ordered. Each item has a unique index
value. The new items will be added to the end of the list.
• Heterogenous: The list can contain different kinds of elements i.e; they can
contain elements of string, integer, boolean, or any type.
• Duplicates: The list can contain duplicates i.e., lists can have two items with
the same values.
Why use a list?
• The list data structure is very flexible It has many unique inbuilt
functionalities like pop(), append(), etc which makes it easier, where the data
keeps changing.
• Also, the list can contain duplicate elements i.e two or more items can have
the same values.
• Lists are Heterogeneous i.e, different kinds of objects/elements can be
added
• As Lists are mutable it is used in applications where the values of the items
change frequently.
• Using list() constructor: In general, the constructor of a class has its class
name. Similarly, Create a list by passing the comma-separated values inside
the list().
• Using square bracket ([]): In this method, we can create a list simply by
enclosing the items inside the square brackets.
Let us see examples for creating the list using the above methods
Run
Length of a List
In order to find the number of items present in a list, we can use
the len() function.
my_list = [1, 2, 3]
print(len(my_list))
# output 3
Run
• Using indexing, we can access any item from a list using its index number
• Using slicing, we can access a range of items from a list
Indexing
The list elements can be accessed using the “indexing” technique. Lists are
ordered collections with unique indexes for each item. We can access the items in
the list using this index number.
Note:
• As Lists are ordered sequences of items, the index values start from 0 to the
Lists length.
• Whenever we try to access an item with an index more than the Lists length,
it will throw the 'Index Error'.
• Similarly, the index values are always an integer. If we give any other type,
then it will throw Type Error.
Example
Run
As seen in the above example we accessed the second element in the list by
passing the index value as 1. Similarly, we passed index 4 to access the 5th
element in the list.
Negative Indexing
The elements in the list can be accessed from right to left by using negative
indexing. The negative value starts from -1 to -length of the list. It indicates that
the list is indexed from the reverse/backward.
Run
As seen in the above example to access the 4th element from the last (right to
left) we pass ‘-4’ in the index value.
List Slicing
Run
Let us see few more examples of slicing a list such as
# Without end_value
# Stating from 3nd item to last item
print(my_list[3:])
# Output [7.5, 'Emma']
Run
Iterating a List
The objects in the list can be iterated over one by one, by using a for a loop.
# iterate a list
for item in my_list:
print(item)
Run
Output
Tom
7.5
Emma
The index value starts from 0 to (length of the list-1). Hence using the function
range() is ideal for this scenario.
Example
Run
Output
Tom
7.5
Emma
The append() method will accept only one parameter and add it at the end of the
list.
Let’s see the example to add the element ‘Emma’ at the end of the list.
# Using append()
my_list.append('Emma')
print(my_list)
# Output [5, 8, 'Tom', 7.5, 'Emma']
Run
Use the insert() method to add the object/item at the specified position in the
list. The insert method accepts two parameters position and object.
insert(index, object)
It will insert the object in the specified index. Let us see this with an example.
# Using insert()
# insert 25 at position 2
my_list.insert(2, 25)
print(my_list)
# Output [5, 8, 25, 'Tom', 7.5]
Run
As seen in the above example item 25 is added at the index position 2.
Using extend()
The extend method will accept the list of elements and add them at the end of
the list. We can even add another list by using this method.
Run
As seen in the above example we have three integer values at once. All the values
get added in the order they were passed and it gets appended at the end of the
list.
Run
print(my_list)
# Output [4, 16, 36, 64]
Run
method Description
remove(item) To remove the first occurrence of the item from the list.
pop(index) Removes and returns the item at the given index from the list.
clear() To remove all items from the list. The output will be an empty list.
Use the remove() method to remove the first occurrence of the item from the list.
Example
my_list = list([2, 4, 6, 8, 10, 12])
# remove item 6
my_list.remove(6)
# remove item 8
my_list.remove(8)
print(my_list)
# Output [2, 4, 10, 12]
Run
print(my_list)
# Output [4, 8, 12]
Run
Use the pop() method to remove the item at the given index. The pop() method
removes and returns the item present at the given index.
Note: It will remove the last time from the list if the index number is not passed.
Example
Run
Use del keyword along with list slicing to remove the range of items
Run
Use the list’ clear() method to remove all items from the list. The clear() method
truncates the list.
# clear list
my_list.clear()
print(my_list)
# Output []
Run
Finding an element in the list
Use the index() function to find an item in a list.
The index() function will accept the value of the element as a parameter and
returns the first occurrence of the element or returns ValueError if the element
does not exist.
print(my_list.index(8))
# Output 3
# returns error since the element does not exist in the list.
# my_list.index(100)
Run
my_list1 = [1, 2, 3]
my_list2 = [4, 5, 6]
# Using + operator
my_list3 = my_list1 + my_list2
print(my_list3)
# Output [1, 2, 3, 4, 5, 6]
Run
Copying a list
There are two ways by which a copy of a list can be created. Let us see each one
with an example.
This is a straightforward way of creating a copy. In this method, the new list will
be a deep copy. The changes that we make in the original list will be reflected in
the new list.
my_list1 = [1, 2, 3]
# Using = operator
new_list = my_list1
# printing the new list
print(new_list)
# Output [1, 2, 3]
Run
As seen in the above example a copy of the list has been created. The changes
made to the original list are reflected in the copied list as well.
Note: When you set list1 = list2, you are making them refer to the
same list object, so when you modify one of them, all references associated with
that object reflect the current state of the object. So don’t use the assignment
operator to copy the dictionary instead use the copy() method.
The copy method can be used to create a copy of a list. This will create a new list
and any changes made in the original list will not reflect in the new list. This
is shallow copying.
my_list1 = [1, 2, 3]
Run
As seen in the above example a copy of the list has been created. The changes
made to the original list are not reflected in the copy.
List operations
We can perform some operations over the list by using certain functions
like sort(), reverse(), clear() etc.
The sort function sorts the elements in the list in ascending order.
mylist = [3,2,1]
mylist.sort()
print(mylist)
Run
Output
[1, 2, 3]
As seen in the above example the items are sorted in the ascending order.
mylist = [3, 4, 5, 6, 1]
mylist.reverse()
print(mylist)
Run
Output
[1, 6, 5, 4, 3]
As seen in the above example the items in the list are printed in the reverse order
here.
mylist = [3, 4, 5, 6, 1]
print(max(mylist)) #returns the maximum number in the list.
print(min(mylist)) #returns the minimum number in the list.
Run
Output
As seen in the above example the max function returns 6 and min function returns
1.
Using sum()
The sum function returns the sum of all the elements in the list.
mylist = [3, 4, 5, 6, 1]
print(sum(mylist))
Run
Output
19
As seen in the above example the sum function returns the sum of all the
elements in the list.
all()
In the case of all() function, the return value will be true only when all the values
inside the list are true. Let us see the different item values and the return values.
#empty list
samplelist4 = []
Run
Output
any()
The any() method will return true if there is at least one true value. In the case of
Empty List, it will return false.
Let us see the same possible combination of values for any() function in a list and
its return values.
Similarly, let’s see each one of the above scenarios with a small example.
#empty list
samplelist4 = []
print("any() Empty list ::",any(samplelist4))
Run
Output
Nested List
The list can contain another list (sub-list), which in turn contains another list and
so on. This is termed a nested list.
Run
In order to retrieve the elements of the inner list we need a nested For-Loop.
nestedlist = [[2,4,6,8,10],[1,3,5,7,9]]
Run
Output
10
1
3
As we can see in the above output the indexing of the nested lists with the index
value of the outer loop first followed by the inner list. We can print values of the
inner lists through a nested for-loop.
List Comprehension
List comprehension is a simpler method to create a list from an existing list. It is
generally a list of iterables generated with an option to include only the items
which satisfy a condition.
inputList = [4,7,11,13,18,20]
#creating a list with square values of only the even numbers
squareList = [var**2 for var in inputList if var%2==0]
print(squareList)
Run
Output
[16, 324, 400]
As seen in the above example we have created a new list from an existing input
list in a single statement. The new list now contains only the squares of the even
numbers present in the input list.
We can even create a list when the input is a continuous range of numbers.
Run
Output
As seen in the above example we have created a list of squares of only even
numbers in a range. The output is again a list so the items will be ordered.
l1 = [10, 20, 30, 40, 50] and l2 = [60, 70, 80, 60]
Operation Description
l1 + l2 Concatenate the lists l1 and l2. Creates a new list containing the items from l1 and l2.
Operation Description
List slicing. Get the items from index i up to index j (excluding j) as a List. An
l1[i:j]
example l1[0:2] is [10, 20]
List slicing with step. Returns a List with the items from index i up to index j taking every k-
l1[i:j:k]
th item. An example l1[0:4:2] is [10, 30].
l2.count(60) Returns the number of times a particular item (60) appears in a list. The answer is 2.
l1.index(30) Returns the index number of a particular item (30) in a list. The answer is 2.
l1.index(30, 2, Returns the index number of a particular item (30) in a list. But search Returns the item with
5) maximum value from a list. The answer is 60 only from index number 2 to 5.
min(l1) Returns the item with a minimum value from a list. The answer is 10.
max(l1) Returns the item with maximum value from a list. The answer is 60.
l1.append([2, 5,
Append the nested list at the end
7])
pop(2) Removes and returns the item at index 2 from the list.