0% found this document useful (0 votes)
14 views8 pages

Day 02 (Module # 2C - Part-1)

This document is a guide on data structures and modules in Python, specifically focusing on lists, tuples, and dictionaries. It explains the characteristics and functionalities of each data structure, providing examples and outputs for better understanding. Additionally, it includes a set of tasks for users to practice their knowledge of these concepts.

Uploaded by

Haya
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)
14 views8 pages

Day 02 (Module # 2C - Part-1)

This document is a guide on data structures and modules in Python, specifically focusing on lists, tuples, and dictionaries. It explains the characteristics and functionalities of each data structure, providing examples and outputs for better understanding. Additionally, it includes a set of tasks for users to practice their knowledge of these concepts.

Uploaded by

Haya
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/ 8

Module # 2C (Part-1) Prepared by:

Data Structure and Modules in Python M. Wasiq Pervez

RASPBERRY PI COURSE GUIDE

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2C (Part-1) Prepared by:
Data Structure and Modules in Python M. Wasiq Pervez

Data Structures
Data structures are basically just that - they are structures which can hold
some data together. In other words, they are used to store a collection of related
data.

There are four built-in data structures in Python - list, tuple, dictionary and set.

Objects
We have not talked about objects yet, but in reality, you've been using them all along.
The secret to Python is that everything is an object. That's right: everything, including
functions and integers.
An object is simply a collection of data stored somewhere in your computer's memory.
What makes an object special in a programming language is the ability for it to store
information and perform actions. We've already seen an object's ability to store data (for
example, a = 3 means that a is an integer object and stores the information 3).

When we use a variable i and assign a value to it, say integer 5 to it, you can think of
it as creating an object (i.e. instance) i of class (i.e. type) int. In fact, you can
read help(int) to understand this better.

Objects are given a set of functions as defined by their class, which acts as a blueprint--
telling the objects what they can and can't do or information it can and can't hold. When
we talk about functions within a class (or objects), we call them methods.

List:
A list is a data structure that holds an ordered collection of items i.e. you can store
a sequence of items in a list. This is easy to imagine if you can think of a shopping list
where you have a list of items to buy, except that you probably have each item on a
separate line in your shopping list whereas in Python you put commas in between
them.

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2C (Part-1) Prepared by:
Data Structure and Modules in Python M. Wasiq Pervez

The list of items should be enclosed in square brackets so that Python understands
that you are specifying a list. Once you have created a list, you can add, remove or
search for items in the list. Since we can add and remove items, we say that a list is
a mutable data type i.e. this type can be altered.

Example:
# This is my shopping list
shoplist = ['apple', 'mango', 'carrot', 'banana']

print('I have', len(shoplist), 'items to purchase.')

print('These items are:', end=' ')


for item in shoplist:
print(item, end=' ')

print('\nI also have to buy rice.')


shoplist.append('rice')
print('My shopping list is now', shoplist)

print('I will sort my list now')


shoplist.sort()
print('Sorted shopping list is', shoplist)

print('The first item I will buy is', shoplist[0])


olditem = shoplist[0]
del shoplist[0]
print('I bought the', olditem)
print('My shopping list is now', shoplist)

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2C (Part-1) Prepared by:
Data Structure and Modules in Python M. Wasiq Pervez

Output:

$ python ds_using_list.py

I have 4 items to purchase.


These items are: apple mango carrot banana
I also have to buy rice.
My shopping list is now ['apple', 'mango', 'carrot', 'banana',
'rice']
I will sort my list now
Sorted shopping list is ['apple', 'banana', 'carrot', 'mango',
'rice']
The first item I will buy is apple
I bought the apple
My shopping list is now ['banana', 'carrot', 'mango', 'rice']

Tuple
Tuples are used to hold together multiple objects. Think of them as similar to lists, but
without the extensive functionality that the list class gives you. One major feature of
tuples is that they are immutable like strings i.e. you cannot modify tuples.

Tuples are defined by specifying items separated by commas within an optional pair
of parentheses.

Tuples are usually used in cases where a statement or a user-defined function can
safely assume that the collection of values (i.e. the tuple of values used) will not
change.

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2C (Part-1) Prepared by:
Data Structure and Modules in Python M. Wasiq Pervez

Example:
# I would recommend always using parentheses
# to indicate start and end of tuple
# even though parentheses are optional.
# Explicit is better than implicit.
zoo = ('python', 'elephant', 'penguin')
print('Number of animals in the zoo is', len(zoo))

new_zoo = 'monkey', 'camel', zoo # parentheses not required


but are a good idea
print('Number of cages in the new zoo is', len(new_zoo))
print('All animals in new zoo are', new_zoo)
print('Animals brought from old zoo are', new_zoo[2])
print('Last animal brought from old zoo is', new_zoo[2][2])
print('Number of animals in the new zoo is',
len(new_zoo)-1+len(new_zoo[2]))

Output:
$ python ds_using_tuple.py

Number of animals in the zoo is 3


Number of cages in the new zoo is 3
All animals in new zoo are ('monkey', 'camel', ('python',
'elephant', 'penguin'))
Animals brought from old zoo are ('python', 'elephant',
'penguin')
Last animal brought from old zoo is penguin
Number of animals in the new zoo is 5

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2C (Part-1) Prepared by:
Data Structure and Modules in Python M. Wasiq Pervez

Dictionary
A dictionary is like an address-book where you can find the address or contact details
of a person by knowing only his/her name i.e. we associate keys (name)
with values (details). Note that the key must be unique just like you cannot find out
the correct information if you have two persons with the exact same name.

Note that you can use only immutable objects (like strings) for the keys of a dictionary
but you can use either immutable or mutable objects for the values of the dictionary.
This basically translates to say that you should use only simple objects for keys.

Pairs of keys and values are specified in a dictionary by using the notation d = {key1
: value1, key2 : value2 }. Notice that the key-value pairs are separated by a colon
and the pairs are separated themselves by commas and all this is enclosed in a pair
of curly braces

Example:

# 'ab' is short for 'a'ddress'b'ook

ab = {
'Swaroop': '[email protected]',
'Larry': '[email protected]',
'Matsumoto': '[email protected]',
'Spammer': '[email protected]'
}

print("Swaroop's address is", ab['Swaroop'])

# Deleting a key-value pair


del ab['Spammer']

print('\nThere are {} contacts in the address-


book\n'.format(len(ab)))

for name, address in ab.items():


print('Contact {} at {}'.format(name, address))

# Adding a key-value pair


ab['Guido'] = '[email protected]'

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2C (Part-1) Prepared by:
Data Structure and Modules in Python M. Wasiq Pervez

if 'Guido' in ab:
print("\nGuido's address is", ab['Guido'])

Output:
$ python ds_using_dict.py
Swaroop's address is [email protected]

There are 3 contacts in the address-book

Contact Swaroop at [email protected]


Contact Matsumoto at [email protected]
Contact Larry at [email protected]

Guido's address is [email protected]

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]
Module # 2C (Part-1) Prepared by:
Data Structure and Modules in Python M. Wasiq Pervez

TASK:
Question # 1:

Ask the user for two integers, and print the addition, subtraction, multiplication, division,
and modulo of those numbers.

Question # 2:

Write a Python function that takes a list of words and returns the length of the longest
one.

Question # 3:

Write a Python function that can find the median among three numbers.

Question # 4:

Write a Python program to test if a variable is a list or tuple.

Question # 5:

Write a Python function that takes two lists and returns True if they have at least one
common member.

Question # 6:

Write a Python program to reverse a tuple (in both string and numbers).

Question # 7:

Write a Python Function to check if a given key already exists in a dictionary.

thingsRoam Academy Contact: +92-308-1222240 academy.thingsroam.com

Email: [email protected]

You might also like