0% found this document useful (0 votes)
60 views71 pages

Tuple, List, Dictionary

Tuples in Python can be used to store ordered and unchangeable collections of items of different data types. Some key points: 1) Tuples are defined using parentheses or the tuple() constructor and allow heterogeneous data types. 2) Once defined, tuples cannot be changed - items cannot be added or removed. 3) Tuples can be accessed using indexing and slicing similar to lists. They also support methods like count, index, and len. 4) Tuples are commonly used to return multiple values from a function or to store immutable data like read-only collections.

Uploaded by

mannalsyed123456
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views71 pages

Tuple, List, Dictionary

Tuples in Python can be used to store ordered and unchangeable collections of items of different data types. Some key points: 1) Tuples are defined using parentheses or the tuple() constructor and allow heterogeneous data types. 2) Once defined, tuples cannot be changed - items cannot be added or removed. 3) Tuples can be accessed using indexing and slicing similar to lists. They also support methods like count, index, and len. 4) Tuples are commonly used to return multiple values from a function or to store immutable data like read-only collections.

Uploaded by

mannalsyed123456
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Tuples in Python

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.

Tuple has the following characteristics

• 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

1. Using parenthesis (): A tuple is created by enclosing comma-separated


items inside rounded brackets.
2. Using a tuple() constructor: Create a tuple by passing the comma-separated
items inside the tuple().

Example

A tuple can have items of different data type integer, float, list, string, etc;

# create a tuple using ()


# number tuple
number_tuple = (10, 20, 25.75)
print(number_tuple)
# Output (10, 20, 25.75)
# string tuple
string_tuple = ('Jessa', 'Emma', 'Kelly')
print(string_tuple)
# Output ('Jessa', 'Emma', 'Kelly')

# mixed type tuple


sample_tuple = ('Jessa', 30, 45.75, [25, 78])
print(sample_tuple)
# Output ('Jessa', 30, 45.75, [25, 78])

# create a tuple using tuple() constructor


sample_tuple2 = tuple(('Jessa', 30, 45.75, [23, 78]))
print(sample_tuple2)
# Output ('Jessa', 30, 45.75, [23, 78])

Run
As we can see in the above output, the different items are added in the tuple like
integer, string, and list.

Create a tuple with a single item

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.

Packing and Unpacking

A tuple can also be created without using a tuple() constructor or enclosing the
items inside the parentheses. It is called the variable “Packing.”

In Python, we can create a tuple by packing a group of variables. Packing can be


used when we want to collect multiple values in a single variable. Generally, this
operation is referred to as tuple packing.

Similarly, we can unpack the items by just assigning the tuple items to the same
number of variables. This process is called “Unpacking.”

Let us see this with an example.

# packing variables into tuple


tuple1 = 1, 2, "Hello"
# display tuple
print(tuple1)
# Output (1, 2, 'Hello')

print(type(tuple1))
# Output class 'tuple'

# unpacking tuple into variable


i, j, k = tuple1
# printing the variables
print(i, j, k)
# Output 1 2 Hello

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.

tuple1 = ('P', 'Y', 'T', 'H', 'O', 'N')


# length of a tuple
print(len(tuple1))
# Output 6

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 .

tuple1 = ('P', 'Y', 'T', 'H', 'O', 'N')


for i in range(4):
print(tuple1[i])

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.

tuple1 = ('P', 'Y', 'T', 'H', 'O', 'N')

# IndexError: tuple index out of range


print(tuple1[7])

Run
Also, if you mention any index value other than integer then it will throw Type
Error.

tuple1 = ('P', 'Y', 'T', 'H', 'O', 'N')

# TypeError: tuple indices must be integers or slices, not float


print(tuple1[2.0])

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].

Let’s do two things here

• Access tuple items using the negative index value


• Iterate tuple using negative indexing
Example

tuple1 = ('P', 'Y', 'T', 'H', 'O', 'N')


# Negative indexing
# print last item of a tuple
print(tuple1[-1]) # N
# print second last
print(tuple1[-2]) # O

# iterate a tuple using negative indexing


for i in range(-6, 0):
print(tuple1[i], end=", ")
# Output P, Y, T, H, O, N,

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.

tuple1 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

# slice a tuple with start and end index number


print(tuple1[1:5])
# Output (1, 2, 3, 4)

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

tuple1 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

# slice a tuple without start index


print(tuple1[:5])
# Output (0, 1, 2, 3, 4)

# slice a tuple without end index


print(tuple1[6:])
# Output (6, 7, 8, 9, 10)

Run
Similarly, we can slice tuple using negative indexing as well. The last but first item
will have the index -1.

tuple1 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

# slice a tuple using negative indexing


print(tuple1[-5:-1])
# Output (6, 7, 8, 9)

Run
Here we can see that the items with the negative indexes starting from -1 till -4
are printed excluding -5.

Finding an item in a Tuple


We can search for a certain item in a tuple using the index() method and it will
return the position of that particular item in the tuple.

The index() method accepts the following three arguments

1. item – The item which needs to be searched


2. start – (Optional) The starting value of the index from which the search will
start
3. end – (Optional) The end value of the index search

Example

tuple1 = (10, 20, 30, 40, 50)

# get index of item 30


position = tuple1.index(30)
print(position)
# Output 2

Run
As seen in the above output the index value of item 30 is printed.

Find within a range

We can mention the start and end values for the index() method so that our
search will be limited to those values.

Example

tuple1 = (10, 20, 30, 40, 50, 60, 70, 80)


# Limit the search locations using start and end
# search only from location 4 to 6
# start = 4 and end = 6
# get index of item 60
position = tuple1.index(60, 4, 6)
print(position)
# Output 5

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.

tuple1 = (10, 20, 30, 40, 50, 60, 70, 80)


#index out of range
position= tuple1 .index(10)
print(postion)
# Output ValueError: tuple.index(x): x not in tuple

Run

Checking if an item exists

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.

Adding and changing items in a Tuple


A list is a mutable type, which means we can add or modify values in it, but tuples
are immutable, so they cannot be changed.

Also, because a tuple is immutable there are no built-in methods to add items to
the tuple.

If you try to modify the value you will get an error.

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)

# converting tuple into a list


sample_list = list(tuple1)
# add item to list
sample_list.append(6)
# converting list back into a tuple
tuple1 = tuple(sample_list)
print(tuple1)
# Output (0, 1, 2, 3, 4, 5, 6)

Run
As we can see in the above output the item is added to the tuple in the end.

Modify nested items of a tuple

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.

tuple1 = (10, 20, [25, 75, 85])

Let’s see how to modify the set item if it contains mutable types.

Example

tuple1 = (10, 20, [25, 75, 85])


# before update
print(tuple1)
# Output (10, 20, [25, 75, 85])

# modify last item's first value


tuple1[2][0] = 250
# after update
print(tuple1)
# Output (10, 20, [250, 75, 85])

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

# converting list back into a tuple


tuple1 = tuple(sample_list)
print(tuple1)
# Output (0, 10, 2, 3, 4, 5)

Run
As we can see in the above output the last item has been updated from 3 to 11.

Removing items from a tuple


Tuples are immutable so there are no pop() or remove() methods for the tuple. We
can remove the items from a tuple using the following two ways.

1. Using del keyword


2. By converting it into a list

Using del keyword

The del keyword will delete the entire tuple.

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.

By converting it into a List

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)

# converting tuple into a list


sample_list = list(tuple1)
# reomve 2nd item
sample_list.remove(2)

# converting list back into a tuple


tuple1 = tuple(sample_list)
print(tuple1)
# Output (0, 1, 3, 4, 5)

Run
As seen in the above output item 3 has been removed from the tuple.

Count the occurrence of an item in a tuple


As we learned, a tuple can contain duplicate items. To determine how many times
a specific item occurred in a tuple, we can use the count() method of a tuple
object.

The count() method accepts any value as a parameter and returns the number of
times a particular value appears in a tuple.

Example

tuple1 = (10, 20, 60, 30, 60, 40, 60)


# Count all occurrences of item 60
count = tuple1.count(60)
print(count)
# Output 3

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)

# converting list back into a tuple2


tuple2 = tuple(sample_list)

# printing the two tuples


print(tuple1)
# Output (0, 1, 2, 3, 4, 5)
print(tuple2)
# Output (0, 1, 2, 3, 4, 5, 6)

Run
As we can see in the above output the tuple1 is not affected by the changes
made in tuple2.

Concatenating two Tuples


We can concatenate two or more tuples in different ways. One thing to note here
is that tuples allow duplicates, so if two tuples have the same item, it will be
repeated twice in the resultant tuple. Let us see each one of them with a small
example.

Using the + operator

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)

# concatenate tuples using + operator


tuple3 = tuple1 + tuple2
print(tuple3)
# Output (1, 2, 3, 4, 5, 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.

Using the sum() function

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)

# using sum function


tuple3 = sum((tuple1, tuple2), ())
print(tuple3)
# Output (1, 2, 3, 4, 5, 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.

Using the chain() function

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

nested_tuple = ((20, 40, 60), (10, 30, 50), "Python")

# access the first item of the third tuple


print(nested_tuple[2][0]) # P

# iterate a nested tuple


for i in nested_tuple:
print("tuple", i, "elements")
for j in i:
print(j, end=", ")
print("\n")

Run
Output

tuple (20, 40, 60) items

20, 40, 60,

tuple (10, 30, 50) items

10, 30, 50,

tuple Python items

P, y, t, h, o, n,

Use built-in functions with tuple

min() and max()

As the name suggests the max() function returns the maximum item in a tuple
and min() returns the minimum value in a tuple.

tuple1 = ('xyz', 'zara', 'abc')


# The Maximum value in a string tuple
print(max(tuple1))
# Output zara

# The minimum value in a string tuple


print(min(tuple1))
# Output abc

tuple2 = (11, 22, 10, 4)


# The Maximum value in a integer tuple
print(max(tuple2))
# Output 22
# The minimum value in a integer tuple
print(min(tuple2))
# Output 4

Run
Note: We can’t find the max() and min() for a heterogeneous tuple (mixed types
of items). It will throw Type Error

tuple3 = ('a', 'e', 11, 22, 15)


# max item
print(max(tuple3))

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.

Item values in a tuple Return value

All values are True True

One or more False values False

All False values False

Empty tuple True

# all() with All True values


tuple1 = (1, 1, True)
print(all(tuple1)) # True

# all() All True values


tuple1 = (1, 1, True)
print(all(tuple1)) # True

# all() with One false value


tuple2 = (0, 1, True, 1)
print(all(tuple2)) # False

# all() with all false values


tuple3 = (0, 0, False)
print(all(tuple3)) # False

# all() Empty tuple


tuple4 = ()
print(all(tuple4)) # True

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.

Item values in a tuple Return value

All values are True True

One or more False values True

All False values False

Empty tuple False

Similarly, let’s see each one of the above scenarios with a small example.

# any() with All True values


tuple1 = (1, 1, True)
print(any(tuple1)) # True

# any() with One false value


tuple2 = (0, 1, True, 1)
print(any(tuple2)) # True

# any() with all false values


tuple3 = (0, 0, False)
print(any(tuple3)) # False

# any() with Empty tuple


tuple4 = ()
print(any(tuple4)) # False

Run

When to use Tuple?


As tuples and lists are similar data structures, and they both allow sequential data
storage, tuples are often referred to as immutable lists. So the tuples are used for
the following requirements instead of lists.

• There are no append() or extend() to add items and similarly


no remove() or pop() methods to remove items. This ensures that the data is
write-protected. As the tuples are Unchangeable, they can be used to
represent read-only or fixed data that does not change.
• As they are immutable, they can be used as a key for the dictionaries, while
lists cannot be used for this purpose.
• As they are immutable, the search operation is much faster than the lists.
This is because the id of the items remains constant.
• Tuples contain heterogeneous (all types) data that offers huge flexibility in
data that contains combinations of data types like alphanumeric characters.

Summary of tuples operations


For the following examples, we assume that t1 and t2 are tuples, x, i, j, k, n are
integers.

t1 = (10, 20, 30, 40, 50) and t2 = (60, 70, 80, 60)

Operation Description

x in t1 Check if the tuple t1 contains the item x.

x not in t2 Check if the tuple t1 does not contain the item x.


Operation Description

t1 + t2 Concatenate the tuples t1 and t2. Creates a new tuple containing the items from t1 and t2.

t1 * 5 Repeat the tuple t1 5 times.

t1[i] Get the item at the index i. Example, t1[2] is 30

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)

len(t1) Returns a count of total items in a tuple

t2.count(60) Returns the number of times a particular item (60) appears in a tuple. Answer is 2

t1.index(30) Returns the index number of a particular item(30) 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.

min(t1) Returns the item with a minimum value from a tuple

max(t1) Returns the item with maximum value from a tuple

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.

Python dictionary represents a mapping between a key and a value. In simple


terms, a Python dictionary can store pairs of keys and values. Each key is linked to
a specific value. Once stored in a dictionary, you can later obtain the value using
just the key.

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:

# create a dictionary using {}


person = {"name": "Jessa", "country": "USA", "telephone": 1178}
print(person)
# output {'name': 'Jessa', 'country': 'USA', 'telephone': 1178}

# create a dictionary using dict()


person = dict({"name": "Jessa", "country": "USA", "telephone": 1178})
print(person)
# output {'name': 'Jessa', 'country': 'USA', 'telephone': 1178}

# create a dictionary from sequence having each item as a pair


person = dict([("name", "Mark"), ("country", "USA"), ("telephone", 1178)])
print(person)

# create dictionary with mixed keys keys


# first key is string and second is an integer
sample_dict = {"name": "Jessa", 10: "Mobile"}
print(sample_dict)
# output {'name': 'Jessa', 10: 'Mobile'}

# create dictionary with value as a list


person = {"name": "Jessa", "telephones": [1178, 2563, 4569]}
print(person)
# output {'name': 'Jessa', 'telephones': [1178, 2563, 4569]}

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.

Accessing elements of a dictionary


There are two different ways to access the elements of a dictionary.

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

# create a dictionary named person


person = {"name": "Jessa", "country": "USA", "telephone": 1178}
# access value using key name in []
print(person['name'])
# Output 'Jessa'

# get key value using key name in get()


print(person.get('telephone'))
# Output 1178

Run
As we can see in the output, we retrieved the value ‘Jessa’ using key ‘name” and
value 1178 using its Key ‘telephone’.

Get all keys and values

Use the following dictionary methods to retrieve all key and values at once

Method Description

keys() Returns the list of all keys present in the dictionary.

values() Returns the list of all values present in the dictionary

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

person = {"name": "Jessa", "country": "USA", "telephone": 1178}

# Get all keys


print(person.keys())
# output dict_keys(['name', 'country', 'telephone'])
print(type(person.keys()))
# Output class 'dict_keys'

# Get all values


print(person.values())
# output dict_values(['Jessa', 'USA', 1178])
print(type(person.values()))
# Output class 'dict_values'
# Get all key-value pair
print(person.items())
# output dict_items([('name', 'Jessa'), ('country', 'USA'), ('telephone', 1178)])
print(type(person.items()))
# Output class 'dict_items'

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.

person = {"name": "Jessa", "country": "USA", "telephone": 1178}

# Iterating the dictionary using for-loop


print('key', ':', 'value')
for key in person:
print(key, ':', person[key])

# using items() method


print('key', ':', 'value')
for key_value in person.items():
# first is key, and second is value
print(key_value[0], key_value[1])

Run
Output

key : value

name : Jessa

country : USA

telephone : 1178

key : value

name Jessa
country USA

telephone 1178

Find a length of a dictionary


In order to find the number of items in a dictionary, we can use
the len() function. Let us consider the personal details dictionary which we
created in the above example and find its length.

person = {"name": "Jessa", "country": "USA", "telephone": 1178}

# count number of keys present in a dictionary


print(len(person))
# output 3

Run

Adding items to the dictionary


We can add new items to the dictionary using the following two ways.

• Using key-value assignment: Using a simple assignment statement where


value can be assigned directly to the new key.
• Using update() Method: In this method, the item passed inside the
update() method will be inserted into the dictionary. The item can be
another dictionary or any iterable like a tuple of key-value pairs.
Now, Let’s see how to add two new keys to the dictionary.

Example

person = {"name": "Jessa", 'country': "USA", "telephone": 1178}

# update dictionary by adding 2 new keys


person["weight"] = 50
person.update({"height": 6})
# print the updated dictionary
print(person)
# output {'name': 'Jessa', 'country': 'USA', 'telephone': 1178, 'weight': 50,
'height': 6}

Run
Note: We can also add more than one key using the update() method.

Example

person = {"name": "Jessa", 'country': "USA"}

# Adding 2 new keys at once


# pass new keys as dict
person.update({"weight": 50, "height": 6})
# print the updated dictionary
print(person)
# output {'name': 'Jessa', 'country': 'USA', 'weight': 50, 'height': 6}

# pass new keys as as list of tuple


person.update([("city", "Texas"), ("company", "Google",)])
# print the updated dictionary
print(person)
# output {'name': 'Jessa', 'country': 'USA', 'weight': 50, 'height': 6, 'city':
'Texas', 'company': 'Google'}

Run

Set default value to a key

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

person_details = {"name": "Jessa", "country": "USA", "telephone": 1178}

# set default value if key doesn't exists


person_details.setdefault('state', 'Texas')
# key doesn't exists and value not mentioned. default None
person_details.setdefault("zip")

# key exists and value mentioned. doesn't change value


person_details.setdefault('country', 'Canada')

# 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.

Modify the values of the dictionary keys


We can modify the values of the existing dictionary keys using the following two
ways.

• 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"}

# updating the country name


person["country"] = "Canada"
# print the updated country
print(person['country'])
# Output 'Canada'

# updating the country name using update() method


person.update({"country": "USA"})
# print the updated country
print(person['country'])
# Output 'USA'

Run

Removing items from the dictionary


There are several methods to remove items from the dictionary. Whether we
want to remove the single item or the last inserted item or delete the entire
dictionary, we can choose the method to be used.

Use the following dictionary methods to remove keys from a dictionary.

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

person = {'name': 'Jessa', 'country': 'USA', 'telephone': 1178, 'weight': 50,


'height': 6}

# Remove last inserted item from the dictionary


deleted_item = person.popitem()
print(deleted_item) # output ('height', 6)
# display updated dictionary
print(person)
# Output {'name': 'Jessa', 'country': 'USA', 'telephone': 1178, 'weight': 50}

# Remove key 'telephone' from the dictionary


deleted_item = person.pop('telephone')
print(deleted_item) # output 1178
# display updated dictionary
print(person)
# Output {'name': 'Jessa', 'country': 'USA', 'weight': 50}

# delete key 'weight'


del person['weight']
# display updated dictionary
print(person)
# Output {'name': 'Jessa', 'country': 'USA'}

# remove all item (key-values) from dict


person.clear()
# display updated dictionary
print(person) # {}

# Delete the entire dictionary


del person

Run

Checking if a key exists


In order to check whether a particular key exists in a dictionary, we can use
the keys() method and in operator. We can use the in operator to check whether
the key is present in the list of keys returned by the keys() method.

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}

# Get the list of keys and check if 'country' key is present


key_name = 'country'
if key_name in person.keys():
print("country name is", person[key_name])
else:
print("Key not found")
# Output country name is USA

Run

Join two dictionary


We can add two dictionaries using the update() method or unpacking arbitrary
keywords operator **. Let us see each one with an example.

Using update() method

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

dict1 = {'Jessa': 70, 'Arul': 80, 'Emma': 55}


dict2 = {'Kelly': 68, 'Harry': 50, 'Olivia': 66}

# copy second dictionary into first dictionary


dict1.update(dict2)
# printing the updated dictionary
print(dict1)
# output {'Jessa': 70, 'Arul': 80, 'Emma': 55, 'Kelly': 68, 'Harry': 50, 'Olivia':
66}

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.

student_dict1 = {'Aadya': 1, 'Arul': 2, }


student_dict2 = {'Harry': 5, 'Olivia': 6}
student_dict3 = {'Nancy': 7, 'Perry': 9}

# join three dictionaries


student_dict = {**student_dict1, **student_dict2, **student_dict3}
# printing the final Merged dictionary
print(student_dict)
# Output {'Aadya': 1, 'Arul': 2, 'Harry': 5, 'Olivia': 6, 'Nancy': 7, 'Perry': 9}

Run
As seen in the above example the values of all the dictionaries have been merged
into one.

Join two dictionaries having few items in common

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

dict1 = {'Jessa': 70, 'Arul': 80, 'Emma': 55}


dict2 = {'Kelly': 68, 'Harry': 50, 'Emma': 66}

# join two dictionaries with some common items


dict1.update(dict2)
# printing the updated dictionary
print(dict1['Emma'])
# Output 66

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

• Using copy() method.


• Using the dict() constructor

dict1 = {'Jessa': 70, 'Emma': 55}

# Copy dictionary using copy() method


dict2 = dict1.copy()
# printing the new dictionary
print(dict2)
# output {'Jessa': 70, 'Emma': 55}

# Copy dictionary using dict() constructor


dict3 = dict(dict1)
print(dict3)
# output {'Jessa': 70, 'Emma': 55}

# Copy dictionary using the output of items() methods


dict4 = dict(dict1.items())
print(dict4)
# output {'Jessa': 70, 'Emma': 55}

Run

Copy using the assignment operator

We can simply use the '=' operator to create a copy.

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}

# Copy dictionary using assignment = operator


dict2 = dict1
# modify dict2
dict2.update({'Jessa': 90})
print(dict2)
# Output {'Jessa': 90, '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.

Let us see an example of creating a nested dictionary ‘Address’ inside a ‘person’


dictionary.

Example

# address dictionary to store person address


address = {"state": "Texas", 'city': 'Houston'}

# dictionary to store person details with address as a nested dictionary


person = {'name': 'Jessa', 'company': 'Google', 'address': address}

# Display dictionary
print("person:", person)

# Get nested dictionary key 'city'


print("City:", person['address']['city'])

# Iterating outer dictionary


print("Person details")
for key, value in person.items():
if key == 'address':
# Iterating through nested dictionary
print("Person Address")
for nested_key, nested_value in value.items():
print(nested_key, ':', nested_value)
else:
print(key, ':', value)

Run
Output

person: {'name': 'Jessa', 'company': 'Google', 'address': {'state': 'Texas', 'city':


'Houston'}}

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.

Add multiple dictionaries inside a single dictionary

Let us see an example of creating multiple nested dictionaries inside a single


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.

For example, class_six['student3']['name']

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

# each dictionary will store data of a single student


jessa = {'name': 'Jessa', 'state': 'Texas', 'city': 'Houston', 'marks': 75}
emma = {'name': 'Emma', 'state': 'Texas', 'city': 'Dallas', 'marks': 60}
kelly = {'name': 'Kelly', 'state': 'Texas', 'city': 'Austin', 'marks': 85}

# Outer dictionary to store all student dictionaries (nested dictionaries)


class_six = {'student1': jessa, 'student2': emma, 'student3': kelly}

# Get student3's name and mark


print("Student 3 name:", class_six['student3']['name'])
print("Student 3 marks:", class_six['student3']['marks'])

# Iterating outer dictionary


print("\nClass details\n")
for key, value in class_six.items():
# Iterating through nested dictionary
# Display each student data
print(key)
for nested_key, nested_value in value.items():
print(nested_key, ':', nested_value)
print('\n')

Run
Output

Student 3 name: Kelly

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

dict1 = {'c': 45, 'b': 95, 'a': 35}

# sorting dictionary by keys


print(sorted(dict1.items()))
# Output [('a', 35), ('b', 95), ('c', 45)]

# sort dict eys


print(sorted(dict1))
# output ['a', 'b', 'c']

# sort dictionary values


print(sorted(dict1.values()))
# output [35, 45, 95]

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

output_dictionary = {key : value for key,value in iterable [if key,value condition1]}

Let us see this with a few examples.

# 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)

# output {2: 4, 8: 64}

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.

telephone_book = [1178, 4020, 5786]


persons = ['Jessa', 'Emma', 'Kelly']

telephone_Directory = {key: value for key, value in zip(persons, telephone_book)}


print(telephone_Directory)
# Output {'Jessa': 1178, 'Emma': 4020, 'Kelly': 5786}

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.

Python Built-in functions with dictionary

max() and min()

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.

Few things to note here are

• Only key values should be true


• The key values can be either True or 1 or ‘0’
• 0 and False in Key will return false
• An empty dictionary will return true.

#dictionary with both 'true' keys


dict1 = {1:'True',1:'False'}

#dictionary with one false key


dict2 = {0:'True',1:'False'}

#empty dictionary
dict3= {}

#'0' is true actually


dict4 = {'0':False}

print('All True Keys::',all(dict1))


print('One False Key',all(dict2))
print('Empty Dictionary',all(dict3))
print('With 0 in single quotes',all(dict4))

Run
Output

All True Keys:: True

One False Key False

Empty Dictionary True

With 0 in single quotes True

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.

#dictionary with both 'true' keys


dict1 = {1:'True',1:'False'}

#dictionary with one false key


dict2 = {0:'True',1:'False'}

#empty dictionary
dict3= {}

#'0' is true actually


dict4 = {'0':False}

#all false
dict5 = {0:False}

print('All True Keys::',any(dict1))


print('One False Key ::',any(dict2))
print('Empty Dictionary ::',any(dict3))
print('With 0 in single quotes ::',any(dict4))
print('all false :: ',any(dict5))

Run
Output

All True Keys:: True

One False Key :: True

Empty Dictionary :: False

With 0 in single quotes :: True

all false :: False

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.

When to use dictionaries?


Dictionaries are items stored in Key-Value pairs that actually use the mapping
format to actually store the values. It uses hashing internally for this. For
retrieving a value with its key, the time taken will be very less as O(1).

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.

Summary of dictionary operations


I want to hear from you. What do you think of this guide on Python dictionaries?
Let me know by leaving a comment below.

Also, try to solve the Python dictionary exercise and dictionary Quiz.

Below is the summary of all operations that we learned in this lesson

Assume d1 and d2 are dictionaries with following items.

d1 = {'a': 10, 'b': 20, 'c': 30}


d2 = {'d': 40, 'e': 50, 'f': 60}

Operations Description

dict({'a': 10, 'b': 20}) Create a dictionary using a dict() constructor.

d2 = {} Create an empty dictionary.

d1.get('a') Retrieve value using the key name a.

d1.keys() Returns a list of keys present in the dictionary.

d1.values() Returns a list with all the values in the dictionary.


Operations Description

Returns a list of all the items in the dictionary with each key-value pair inside a
d1.items()
tuple.

len(d1) Returns number of items in a dictionary.

d1['d'] = 40 Update dictionary by adding a new key.

d1.update({'e': 50, 'f':


Add multiple keys to the dictionary.
60})

d1.setdefault('g', 70) Set the default value if a key doesn’t exist.

d1['b'] = 100 Modify the values of the existing key.

d1.pop('b') Remove the key b from the dictionary.

d1.popitem() Remove any random item from a dictionary.

d1.clear() Removes all items from the dictionary.

'key' in d1.keys() Check if a key exists in a dictionary.

d1.update(d2) Add all items of dictionary d2 into d1.

d3= {**d1, **d2} Join two dictionaries.

d2 = d1.copy() Copy dictionary d1 into d2.

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 Exercise


• Python List Quiz
• Summary of List Operations

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.

Creating a Python list


The list can be created using either the list constructor or using square
brackets [].

• 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

# Using list constructor


my_list1 = list((1, 2, 3))
print(my_list1)
# Output [1, 2, 3]

# Using square brackets[]


my_list2 = [1, 2, 3]
print(my_list2)
# Output [1, 2, 3]

# with heterogeneous items


my_list3 = [1.0, 'Jessa', 3]
print(my_list3)
# Output [1.0, 'Jessa', 3]

# empty list using list()


my_list4 = list()
print(my_list4)
# Output []

# empty list using []


my_list5 = []
print(my_list4)
# Output []

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

Accessing items of a List


The items in a list can be accessed through indexing and slicing. This section will
guide you by accessing the list using the following two ways

• 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.

Python Positive and Negative indexing


To access the elements in the list from left to right, the index value starts
from zero to (length of the list-1) can be used. For example, if we want to
access the 3rd element we need to use 2 since the index value starts from 0.

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

my_list = [10, 20, 'Jessa', 12.50, 'Emma']


# accessing 2nd element of the list
print(my_list[1]) # 20
# accessing 5th element of the list
print(my_list[4]) # 'Emma'

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.

my_list = [10, 20, 'Jessa', 12.50, 'Emma']


# accessing last element of the list
print(my_list[-1])
# output 'Emma'

# accessing second last element of the list


print(my_list[-2])
# output 12.5

# accessing 4th element from last


print(my_list[-4])
# output 20

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

Slicing a list implies, accessing a range of elements in a list. For example, if we


want to get the elements in the position from 3 to 7, we can use the slicing
method. We can even modify the values in a range by using this slicing
technique.

The below is the syntax for list slicing.

listname[start_index : end_index : step]


• The start_index denotes the index position from where the slicing should
begin and the end_index parameter denotes the index positions till which the
slicing should be done.
• The step allows you to take each nth-element within
a start_index:end_index range.
Example

my_list = [10, 20, 'Jessa', 12.50, 'Emma', 25, 50]


# Extracting a portion of the list from 2nd till 5th element
print(my_list[2:5])
# Output ['Jessa', 12.5, 'Emma']

Run
Let us see few more examples of slicing a list such as

• Extract a portion of the list


• Reverse a list
• Slicing with a step
• Slice without specifying start or end position
Example

my_list = [5, 8, 'Tom', 7.50, 'Emma']

# slice first four items


print(my_list[:4])
# Output [5, 8, 'Tom', 7.5]

# print every second element


# with a skip count 2
print(my_list[::2])
# Output [5, 'Tom', 'Emma']

# reversing the list


print(my_list[::-1])
# Output ['Emma', 7.5, 'Tom', 8, 5]

# 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.

my_list = [5, 8, 'Tom', 7.50, 'Emma']

# iterate a list
for item in my_list:
print(item)

Run
Output

Tom

7.5

Emma

Iterate along with an index number

The index value starts from 0 to (length of the list-1). Hence using the function
range() is ideal for this scenario.

The range function returns a sequence of numbers. By default, it returns starting


from 0 to the specified number (increments by 1). The starting and ending values
can be passed according to our needs.

Example

my_list = [5, 8, 'Tom', 7.50, 'Emma']


# iterate a list
for i in range(0, len(my_list)):
# print each item using index number
print(my_list[i])

Run
Output

Tom

7.5

Emma

Adding elements to the list


We can add a new element/list of elements to the list using the list methods such
as append(), insert(), and extend().

Append item at the end of the list

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.

my_list = list([5, 8, 'Tom', 7.50])

# Using append()
my_list.append('Emma')
print(my_list)
# Output [5, 8, 'Tom', 7.5, 'Emma']

# append the nested list at the end


my_list.append([25, 50, 75])
print(my_list)
# Output [5, 8, 'Tom', 7.5, 'Emma', [25, 50, 75]]

Run

Add item at the specified position in the list

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.

my_list = list([5, 8, 'Tom', 7.50])

# Using insert()
# insert 25 at position 2
my_list.insert(2, 25)
print(my_list)
# Output [5, 8, 25, 'Tom', 7.5]

# insert nested list at at position 3


my_list.insert(3, [25, 50, 75])
print(my_list)
# Output [5, 8, 25, [25, 50, 75], '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.

Let’s add three items at the end of the list.

my_list = list([5, 8, 'Tom', 7.50])


# Using extend()
my_list.extend([25, 75, 100])
print(my_list)
# Output [5, 8, 'Tom', 7.5, 25, 75, 100]

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.

Modify the items of a List


The list is a mutable sequence of iterable objects. It means we can modify the
items of a list. Use the index number and assignment operator ( =) to assign a new
value to an item.

Let’s see how to perform the following two modification scenarios

• Modify the individual item.


• Modify the range of items

my_list = list([2, 4, 6, 8, 10, 12])

# modify single item


my_list[0] = 20
print(my_list)
# Output [20, 4, 6, 8, 10, 12]

# modify range of items


# modify from 1st index to 4th
my_list[1:4] = [40, 60, 80]
print(my_list)
# Output [20, 40, 60, 80, 10, 12]

# modify from 3rd index to end


my_list[3:] = [80, 100, 120]
print(my_list)
# Output [20, 40, 60, 80, 100, 120]

Run

Modify all items


Use for loop to iterate and modify all items at once. Let’s see how to modify each
item of a list.

my_list = list([2, 4, 6, 8])

# change value of all items


for i in range(len(my_list)):
# calculate square of each number
square = my_list[i] * my_list[i]
my_list[i] = square

print(my_list)
# Output [4, 16, 36, 64]

Run

Removing elements from a List


The elements from the list can be removed using the following list methods.

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.

del list_name Delete the entire list.

Python List methods to remove item

Remove specific item

Use the remove() method to remove the first occurrence of the item from the list.

Note: It Throws a keyerror if an item not present in the original 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

Remove all occurrence of a specific item

Use a loop to remove all occurrence of a specific item

my_list = list([6, 4, 6, 6, 8, 12])

for item in my_list:


my_list.remove(6)

print(my_list)
# Output [4, 8, 12]

Run

Remove item present at given index

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

my_list = list([2, 4, 6, 8, 10, 12])

# remove item present at index 2


my_list.pop(2)
print(my_list)
# Output [2, 4, 8, 10, 12]
# remove item without passing index number
my_list.pop()
print(my_list)
# Output [2, 4, 8, 10]

Run

Remove the range of items

Use del keyword along with list slicing to remove the range of items

my_list = list([2, 4, 6, 8, 10, 12])

# remove range of items


# remove item from index 2 to 5
del my_list[2:5]
print(my_list)
# Output [2, 4, 12]

# remove all items starting from index 3


my_list = list([2, 4, 6, 8, 10, 12])
del my_list[3:]
print(my_list)
# Output [2, 4, 6]

Run

Remove all items

Use the list’ clear() method to remove all items from the list. The clear() method
truncates the list.

my_list = list([2, 4, 6, 8, 10, 12])

# clear list
my_list.clear()
print(my_list)
# Output []

# Delete entire list


del my_list

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.

my_list = list([2, 4, 6, 8, 10, 12])

print(my_list.index(8))
# Output 3

# returns error since the element does not exist in the list.
# my_list.index(100)

Run

Concatenation of two lists


The concatenation of two lists means merging of two lists. There are two ways to
do that.

• Using the + operator.


• Using the extend() method. The extend() method appends the new list’s
items at the end of the calling list.
Example

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]

# Using extend() method


my_list1.extend(my_list2)
print(my_list1)
# 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.

Using assignment operator (=)

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.

This is called deep copying.

my_list1 = [1, 2, 3]

# Using = operator
new_list = my_list1
# printing the new list
print(new_list)
# Output [1, 2, 3]

# making changes in the original list


my_list1.append(4)

# print both copies


print(my_list1)
# result [1, 2, 3, 4]
print(new_list)
# result [1, 2, 3, 4]

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.

Using 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]

# Using copy() method


new_list = my_list1.copy()
# printing the new list
print(new_list)
# Output [1, 2, 3]

# making changes in the original list


my_list1.append(4)

# print both copies


print(my_list1)
# result [1, 2, 3, 4]
print(new_list)
# result [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.

Sort List using sort()

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.

Reverse a List using reverse()

The reverse function is used to reverse the elements in the list.

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.

Python Built-in functions with List


In addition to the built-in methods available in the list, we can use the built-in
functions as well on the list. Let us see a few of them for example.

Using max() & min()


The max function returns the maximum value in the list while the min function
returns the minimum value in the list.

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.

Item Values in List Return Value

All Values are True True

One or more False Values False

All False Values False

Empty List True

#with all true values


samplelist1 = [1,1,True]
print("all() All True values::",all(samplelist1))

#with one false


samplelist2 = [0,1,True,1]
print("all() with One false value ::",all(samplelist2))

#with all false


samplelist3 = [0,0,False]
print("all() with all false values ::",all(samplelist3))

#empty list
samplelist4 = []

Run
Output

all() All True values:: True

all() with One false value :: False

all() with all false values :: False

all() Empty list :: True

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.

Item Values in List Return Value

All Values are True True

One or more False Values True

All False Values False

Empty List False

Similarly, let’s see each one of the above scenarios with a small example.

#with all true values


samplelist1 = [1,1,True]
print("any() True values::",any(samplelist1))

#with one false


samplelist2 = [0,1,True,1]
print("any() One false value ::",any(samplelist2))

#with all false


samplelist3 = [0,0,False]
print("any() all false values ::",any(samplelist3))

#empty list
samplelist4 = []
print("any() Empty list ::",any(samplelist4))

Run
Output

any() True values:: True

any() One false value :: True

any() all false values :: False


any() Empty list :: False

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.

mylist = [3, 4, 5, 6, 3, [1, 2, 3], 4]

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]]

print("Accessing the third element of the second list",nestedlist[1][2])


for i in nestedlist:
print("list",i,"elements")
for j in i:
print(j)

Run
Output

Accessing the third element of the second list 5

list [2, 4, 6, 8, 10] elements

10

list [1, 3, 5, 7, 9] elements

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.

outputList = {expression(variable) for variable in inputList [if variable


condition1][if variable condition2]

• expression:Optional. expression to compute the members of the output List


which satisfies the optional conditions
• variable: Required. a variable that represents the members of the input List.
• inputList: Required. Represents the input set.
• condition1, condition2 etc; : Optional. Filter conditions for the members of the
output List.

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.

#creating even square list for a range of numbers


squarelist1 = [s**2 for s in range(10)if s%2 == 0]
print(squarelist1)

Run
Output

[0, 4, 16, 36, 64]

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.

Summary of List operations


For the following examples, we assume that l1 and l2 are lists, x, i, j, k, n are
integers.

l1 = [10, 20, 30, 40, 50] and l2 = [60, 70, 80, 60]

Operation Description

x in l1 Check if the list l1 contains item x.

x not in l2 Check if list l1 does not contain item x.

l1 + l2 Concatenate the lists l1 and l2. Creates a new list containing the items from l1 and l2.
Operation Description

l1 * 5 Repeat the list l1 5 times.

l1[i] Get the item at index i. Example l1[2] is 30.

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].

len(l1) Returns a count of total items in a list.

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(100) Add item at the end of the list

l1.append([2, 5,
Append the nested list at the end
7])

l1[2] = 40 Modify the item present at index 2

l1.remove(40) Removes the first occurrence of item 40 from the list.

pop(2) Removes and returns the item at index 2 from the list.

l1.clear() Make list empty


Operation Description

l3= l1.copy() Copy l1 into l2

You might also like