0% found this document useful (0 votes)
4 views

Chapter_6

Chapter 6 of 'Problem Solving and Programming with Python' by Reema Thareja discusses data structures in Python, focusing on sequences, lists, tuples, and dictionaries. It explains the characteristics, operations, and use cases of each data structure, highlighting the differences between them and when to use each type. The chapter also covers advanced list processing techniques, such as list comprehensions and built-in functions like map, filter, and reduce.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Chapter_6

Chapter 6 of 'Problem Solving and Programming with Python' by Reema Thareja discusses data structures in Python, focusing on sequences, lists, tuples, and dictionaries. It explains the characteristics, operations, and use cases of each data structure, highlighting the differences between them and when to use each type. The chapter also covers advanced list processing techniques, such as list comprehensions and built-in functions like map, filter, and reduce.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

Problem Solving and

Programming with

Python
Reema Thareja
Chapter 6: Lists, Tuples,
and Dictionaries

© Oxford University Press 2019. All rights reserved.


Data Structure: Sequence

• A data structure is a group of data elements that are put together under one name. Data structure defines a

• particular way of storing and organizing data in a computer so that it can be used efficiently.

• Sequence is the most basic data structure in Python. In sequence, each element has a specific index. This index value
starts from zero and is automatically incremented for the next element. In Python, sequence is the generic term for an
ordered set. For example, we have already studied strings which are a sequence of characters.

• Python has some basic built-in functions that help programmers to manipulate elements that form a part

• of a sequence. These functions include finding the length of a sequence, finding the largest and smallest

• elements in a sequence, etc. Other operations that can be performed on a sequence include indexing, slicing,

• adding, multiplying, and checking for membership.

© Oxford University Press 2019. All rights reserved. 3


Lists
List is a versatile data type available in Python. It is a sequence in which elements are written as a list of
comma-separated values (items) between square brackets. The key feature of a list is that it can have
elements that belong to different data types. The syntax of defining a list can be given as,

List_variable = [val1, val2,...]

Examples:

© Oxford University Press 2019. All rights reserved. 4


Access Values in Lists

Similar to strings, lists can also be sliced and concatenated. To access values in lists, square brackets are
used to slice along with the index or indices to get value stored at that index. The syntax for the slice
operation is given as, seq = List[start:stop:step]

Example:

© Oxford University Press 2019. All rights reserved. 5


Updating Values in Lists

Once created, one or more elements of a list can be easily updated by giving the slice on the left-hand side
of the assignment operator. You can also append new values in the list and remove existing value(s) from
the list using the append() method and del statement, respectively.

Example:

© Oxford University Press 2019. All rights reserved. 6


Nested Lists

Nested list means a list within another list. We have already said that a list has elements
of different data types which can include even a list.

Example:

© Oxford University Press 2019. All rights reserved. 7


Cloning Lists

If you want to modify a list and also keep a copy of the original list, then you should create a separate copy
of the list (not just the reference). This process is called cloning. The slice operation is used to clone a list.

Example:

© Oxford University Press 2019. All rights reserved. 8


Basic List Operations

© Oxford University Press 2019. All rights reserved. 9


Basic List Operations

© Oxford University Press 2019. All rights reserved. 10


List Methods

© Oxford University Press 2019. All rights reserved. 11


List Methods

© Oxford University Press 2019. All rights reserved. 12


Lists as Arrays
In Python, an array of numeric values is supported through the array module. We can treat lists as arrays. While a list can store
elements of multiple data types, an array contains elements only of the same type. Therefore, we can say that, array is a container
which can store a fixed number of elements that are of the same type.
Some important terms that are frequently used while working with arrays:
Element—Each item stored in an array.
Index—Location of each element in the array is denoted by a numerical index. Every element is identified with its index in to the array.
The index of the first element is 0, second element is 1, third element is 2, so on and so forth.

An array of length 10

Creating an Array

© Oxford University Press 2019. All rights reserved. 13


Lists as Arrays
Example:

© Oxford University Press 2019. All rights reserved. 14


Advanced List Processing
Python also supports computed lists called list comprehensions having the following syntax.

List = [expression for variable in sequence]

Where, the expression is evaluated once, for every item in the sequence.

List comprehensions help programmers to create lists in a concise way. This is mainly beneficial to make new lists where each element
is the obtained by applying some operations to each member of another sequence or iterable. List comprehension is also used to

create a subsequence of those elements that satisfy a certain condition .


Example:

© Oxford University Press 2019. All rights reserved. 15


Looping in Lists

Python's for and in constructs are extremely useful especially when working with lists. The for var in list statement is an
easy way to access each element in a list (or any other sequence). For example, in the following code, the for loop is
used to access each item in the list.
Example
for i in list:

print(i)

© Oxford University Press 2019. All rights reserved. 16


Using the enumerate() and range() Functions

• enumerate() function is used when you want to print both index as well as an item in the list. The function returns an
enumerate object which contains the index and value of all the items of the list as a tuple.

• The range() function is used when you need to print index.

Examples:

© Oxford University Press 2019. All rights reserved. 17


Using an Iterator

You can create an iterator using the built-in iter() function. The iterator is used to loop over the elements of
the list. For this, the iterator fetches the value and then automatically points to the next element in the list
when it is used with the next() method.

Example:

© Oxford University Press 2019. All rights reserved. 18


filter() Function

The filter() function constructs a list from those elements of the list for which a function returns True. The syntax of the
filter() function is given as, filter(function, sequence)

As per the syntax, the filter() function returns a sequence that contains items from the sequence for which the function
is True. If sequence is a string, Unicode, or a tuple, then the result will be of the same type; otherwise, it is always a list.

Example:

© Oxford University Press 2019. All rights reserved. 19


map() Function

The map() function applies a particular function to every element of a list. Its syntax is same as the filter
function:

After applying the specified function on the sequence, the map() function returns the modified list. The
map() function calls function(item) for each item in the sequence and returns a list of the return values.
Example: Program that adds 2 to every value in the list

© Oxford University Press 2019. All rights reserved. 20


reduce() Function

The reduce() function with syntax as given below returns a single value generated by calling the function on
the first two items of the sequence, then on the result and the next item, and so on.

Example: Program to calculate the sum of values in a list using the reduce() function

© Oxford University Press 2019. All rights reserved. 21


Tuple
• Like lists, tuple is another data structure supported by Python. It is very similar to lists but differs in two
things.

• • First, a tuple is a sequence of immutable objects. This means that while you can change the value of one
or more items in a list, you cannot change the values in a tuple.

• • Second, tuples use parentheses to define its elements whereas lists use square brackets.

• Creating Tuple

• Creating a tuple is very simple and almost similar to creating a list. For creating a tuple, generally you need
to just put the different comma-separated values within a parentheses as shown below.

• Tup1 = (val 1, val 2,...)

• where val (or values) can be an integer, a floating number, a character, or a string.

© Oxford University Press 2019. All rights reserved. 22


Utility of Tuples

In real-world applications, tuples are extremely useful for representing records or structures as we call in other
programming languages. These structures store related information about a subject together. The information belongs
to different data types.

For example, a tuple that stores information about a student can have elements like roll_no, name, course, total marks,
avg, etc. Some built-in functions return a tuple. For example, the divmod() function returns two values—quotient as
well as the remainder after performing the divide operation.

Examples:

© Oxford University Press 2019. All rights reserved. 23


Accessing Values in a Tuple

Like other sequences (strings and lists) covered so far, indices in a tuple also starts at 0. You can even perform
operations like slice, concatenate, etc. on a tuple. For example, to access values in tuple, slice operation is used along
with the index or indices to obtain value stored at that index.

Example:

© Oxford University Press 2018. All rights reserved. 24


Deleting Elements in Tuple

Since tuple is an immutable data structure, you cannot delete value(s) from it. Of course,
you can create a new tuple that has all elements in your tuple except the ones you don't
want (those you wanted to be deleted).
Examples

© Oxford University Press 2019. All rights reserved. 25


Basic Tuple Operations

© Oxford University Press 2019. All rights reserved. 26


Tuple Assignment

Tuple assignment is a very powerful feature in Python. It allows a tuple of variables on the left side of the assignment
operator to be assigned values from a tuple given on the right side of the assignment operator.

Each value is assigned to its respective variable. In case, an expression is specified on the right side of the assignment
operator, first that expression is evaluated and then assignment is done.

Example:

© Oxford University Press 2019. All rights reserved. 27


Tuples for Returning Multiple Values and Nested Tuples

Examples

© Oxford University Press 2019. All rights reserved. 28


Checking the Index: index() method

The index of an element in the tuple can be obtained by using the index() method. If the element being
searched is not present in the list, then error is generated. The syntax of index() is given as, list.index(obj)
where, obj is the object to be found out.

Examples:

© Oxford University Press 2019. All rights reserved. 29


count()Method and List Comprehension and Tuples
Examples

© Oxford University Press 2019. All rights reserved. 30


Variable-length Argument Tuples

Many built-in functions like max(), min(), sum(), etc. use variable-length arguments since these functions
themselves do not know how many arguments will be passed to them. It allows a function to accept a
variable (different) number of arguments. This is especially useful in defining functions that are applicable
to a large variety of arguments. For example, if you have a function that displays all the parameters passed
to it, then even the function does not know how many values it will be passed. In such cases, we use a
variable-length argument that begins with a '*' symbol. Any argument that starts with a '*' symbol is known
as gather and specifies a variable-length argument.

Example:

© Oxford University Press 2019. All rights reserved. 31


The zip() Function

The zip() is a built-in function that takes two or more sequences and "zips"
them into a list of tuples. The tuple thus, formed has one element from each
sequence.

Example: Program to show the use of zip() function

© Oxford University Press 2019. All rights reserved. 32


Advantages of Tuple over List

• Tuples are used to store values of different data types. Lists can however, store data of similar data types.

• Since tuples are immutable, iterating through tuples is faster than iterating over a list. This means that a tuple performs
better than a list.

• Tuples can be used as key for a dictionary but lists cannot be used as keys.

• Tuples are best suited for storing data that is write-protected.

• Tuples can be used in place of lists where the number of values is known and small.

• If you are passing a tuple as an argument to a function, then the potential for unexpected behavior due to aliasing gets
reduced.

• Multiple values from a function can be returned using a tuple.

• Tuples are used to format strings.

© Oxford University Press 2019. All rights reserved. 33


Dictionaries
Dictionary is a data structure in which we store values as a pair of key and value. Each key is separated from its value by
a colon (:), and consecutive items are separated by commas. The entire items in a dictionary are enclosed in curly
brackets({}). The syntax for defining a dictionary is

dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3}

If there are many keys and values in dictionaries, then we can also write just one key-value pair on a line to make the
code easier to read and understand. This is shown below.

dictionary_name = {key_1: value_1, key_2: value_2, key_3: value_3, ….}

Example:

© Oxford University Press 2019. All rights reserved. 34


Accessing Values

• Example:

© Oxford University Press 2019. All rights reserved. 35


Adding and Modifying an Item in a Dictionary

• Example:

© Oxford University Press 2019. All rights reserved. 36


Modifying an Entry

• Example:

© Oxford University Press 2019. All rights reserved. 37


Sorting Items and Looping over Items in a Dictionary
• Examples:

© Oxford University Press 2019. All rights reserved. 38


Nested Dictionaries

• Example:

© Oxford University Press 2019. All rights reserved. 39


Built-in Dictionary Functions and Methods

© Oxford University Press 2019. All rights reserved. 40


Built-in Dictionary Functions and Methods

© Oxford University Press 2019. All rights reserved. 41


Built-in Dictionary Functions and Methods

© Oxford University Press 2019. All rights reserved. 42


Difference between a List and a Dictionary

• First, a list is an ordered set of items. But, a dictionary is a data structure that is used for matching one item
(key) with another (value).

• Second, in lists, you can use indexing to access a particular item. But, these indexes should be a number. In
dictionaries, you can use any type (immutable) of value as an index. For example, when we write
Dict['Name'], Name acts as an index but it is not a number but a string.

• Third, lists are used to look up a value whereas a dictionary is used to take one value and look up another
value. For this reason, dictionary is also known as a lookup table.

• Fourth, the key-value pair may not be displayed in the order in which it was specified while defining the
dictionary. This is because Python uses complex algorithms (called hashing) to provide fast access to the
items stored in the dictionary. This also makes dictionary preferable to use over a list of tuples.

© Oxford University Press 2019. All rights reserved. 43


String Formatting with Dictionaries

Python also allows you to use string formatting feature with dictionaries. So you can use %s, %d, %f, etc. to
represent string, integer, floating point number, or any other data.

Example: Program that uses string formatting feature to print the key-value pairs stored in the dictionary

© Oxford University Press 2019. All rights reserved. 44


When to use which Data Structure?

• Use lists to store a collection of data that does not need random access.

• Use lists if the data has to be modified frequently.

• Use a set if you want to ensure that every element in the data structure
must be unique.

• Use tuples when you want that your data should not be altered.

© Oxford University Press 2019. All rights reserved. 45

You might also like