You are on page 1of 12

Lab Experiment | 11

LAB # 11
To demonstrate ability to use lists, tuples, dictionaries in Python code
Objectives
 In this lab, you will practice code with Python strings, lists, tuples, dictionaries.
 You will practice loops and their common usage in code.
Lab Exercise

Python has several important data types, other than the usual integer, float, string, and Boolean
types, that come in handy. They are called lists, tuples, and dictionaries.

Strings

Strings are usually created in one of three ways. You can use single, double or triple quotes.

The triple quoted line can be done with three single quotes or three double quotes. Either way, they allow the
programmer to write strings over multiple lines. If you print it out, you will notice that the output retains the
line breaks. If you need to use single quotes in your string, then wrap it in double quotes.

There is other way to create a string and that is by using the str method. Here’s how it works:

If you type the code above into your interpreter, you’ll find that you have transformed the integer value into a
string and assigned the string to the variable my_string. This is known as casting. You can cast some data types
into other data types, like numbers into strings. But you’ll also find that you can’t always do the reverse, such as
casting a string like ‘ABC’ into an integer.

It should be noted that a string is one of Python immutable types. What this means is that you cannot change a
string’s content after creation. Let’s try to change one to see what happens:

We have already studied in previous labs how strings can be concatenated using the + operator. Let
us practice few more methods on strings:

Try the following codes, their functionality is self-evident:

Page 1 of 12
Lab Experiment | 11

my_string = "This is a string!"


my_string.upper()
help(my_string.capitalize) #the help function was discussed in class
String indexing:

my_string = "I like Python!"


my_string[0] #first index of the string
my_string[14] #last index of the string
my_string[-1] #also last index of the string
String slicing:

Lists

A Python list is similar to an array in other languages. In Python, an empty list can be created in the
following ways.

As you can see, you can create the list using square brackets or by using the Python built-in, list. A list contains
a list of elements, such as strings, integers, objects or a mixture of types. Let’s take a look at some examples:

The first list has 3 integers, the second has 3 strings and the third has a mixture. You can also create
lists of lists like this:

Occasionally, you’ll want to combine two lists together. The first way is to use the extend method:

Page 2 of 12
Lab Experiment | 11

A slightly easier way is to just add two lists together.

Yes, it really is that easy. You can also sort a list. Let’s spend a moment to see how to do that:

You need to take care of assignment operator in Python, as demonstrated below:

In this example, we try to assign the sorted list to a variable. However, when you call
the sort() method on a list, it sorts the list in-place. So if you try to assign the result to another
variable, then you’ll find out that you’ll get a None object, which is like a Null in other languages. Thus
when you want to sort something, just remember that you sort them in-place and you cannot assign it
to a different variable.

You can slice a list just like you do with a string:

This code returns a list of just the first 3 elements.

Tuples

A tuple is similar to a list, but you create them with parentheses instead of square brackets. You can
also use the tuple built-in. The main difference is that a tuple is immutable while the list is mutable.
Let’s take a look at a few examples:

Page 3 of 12
Lab Experiment | 11

The code above demonstrates one way to create a tuple with five elements. It also shows that you
can do tuple slicing. However, you cannot sort a tuple! The last two examples shows how to create
tuples using the tuple keyword. The first one just creates an empty tuple whereas the second
example has three elements inside it. Notice that it has a list inside it. This is an example of casting.
We can change or cast an item from one data type to another. In this case, we cast a list into a tuple.
If you want to turn the abc tuple back into a list, you can do the following:

To reiterate, the code above casts the tuple (abc) into a list using the list function.

Dictionaries

A Python dictionary is basically a hash table or a hash mapping. In some languages, they might be
referred to as associative memories or associative arrays. They are indexed with keys, which can be
any immutable type. For example, a string or number can be a key. You need to be aware that a
dictionary is an unordered set of key:value pairs and the keys must be unique. You can get a list of
keys by calling a dictionary instance’s keys method. To check if a dictionary has a key, you can use
Python’s in keyword.

Let’s take a moment to see how we create a dictionary.

The first two examples show how to create an empty dictionary. All dictionaries are enclosed with
curly braces. The last line is printed out so you can see how unordered a dictionary is. Now it’s time
to find out how to access a value in a dictionary.

Page 4 of 12
Lab Experiment | 11

In the first example, we use the dictionary from the previous example and pull out the value
associated with the key called “one”. The second example shows how to acquire the value for the
“name” key. Now let’s see how to tell if a key is in a dictionary or not:

So, if the key is in the dictionary, Python returns a Boolean True. Otherwise it returns a
Boolean False. If you need to get a listing of all the keys in a dictionary, then you do this:

The keys method returns a view object. This gives the developer the ability to update the dictionary
and the view will automatically update too. Also note that when using the in keyword for dictionary
membership testing, it is better to do it against the dictionary instead of the list returned from
the keys method. See below:

While this probably won’t matter much to you right now, in a real job situation, seconds matter. When
you have thousands of files to process, these little tricks can save you a lot of time in the long run!

update() method:

keys() method:

Page 5 of 12
Lab Experiment | 11

values() method:

pop() method:

get() method:

Page 6 of 12
Lab Experiment | 11

Sets

Strings are usually created in one of three ways. You can use single, double or triple quotes.

A set is a collection which is unordered, unchangeable (you can remove items and add new items, but not
change items), and unindexed.

Sets are written with curly brackets.

Sets cannot have two items with the same value.

In a set, True and 1 is considered the same value. The values False and 0 are considered the same value.

A set can contain different data types:

It is also possible to use the set() constructor to make a set.

Page 7 of 12
Lab Experiment | 11

For loop

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

This is less like the for keyword in other programming languages and works more like an iterator method as
found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.

Even strings are iterable objects, they contain a sequence of characters:

With the break statement we can stop the loop before it has looped through all the items:

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.

Start range from 2:

Set increment to 3:

Page 8 of 12
Lab Experiment | 11

The else keyword in a for loop specifies a block of code to be executed when the loop is finished:

The else block will NOT be executed if the loop is stopped by a break statement.

A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement
to avoid getting an error.

While loop

With the while loop we can execute a set of statements as long as a condition is true.

The break, continue, pass and else statements work the same was as described for the for loop.

Page 9 of 12
Lab Experiment | 11

The code below summarizes few concepts discussed above, using while loop:

# Python program to square every number of a list

# initializing a list

list_ = [3, 5, 1, 4, 6]
squares = []
while list_: #this expression returns True until the list is empty
squares.append( (list_.pop())**2)
print(squares)

Exercise 1
Define a list of integers. Write a Python program to split the list into two parts. Use a variable to define length
of the first list required. Display both lists at the end.

Hint: you can slice a list.

Exercise 2
Create a python dictionary where the values are a list. For example:

{'K1': [1, 2, 3], 'K2': [‘a’, ‘b’, ‘c’], 'K3': {'A': 'Welcome', 'B': 'To', 'C':
'COMSATS'}}

Then clear all the values (for all the keys) in the dictionary and the dictionary should look like this:

{'K1': [], 'K2': [], 'K3': []}

Hint: The clear() method erases values of a dictionary, list and set. You can loop over the dictionary
items like below:

for key in dictionary:

You can use clear() method in following way:

dictionary[key].clear()

Page 10 of 12
Lab Experiment | 11

Exercise 3
Define a function that takes a string as input. The function then counts the number of upper case and lower-case
characters in the string.

Hint: In the function, you can create a dictionary like d = {"UPPER_CASE": 0, "LOWER_CASE": 0} to
keep count of both categories.

You can use a loop in the function over all characters of string using previously discussed process like for
characters_ in string_:

On string and characters, you use built-in function characters_.isupper() and


characters_.islower() to find out category of character. You can then increment value of relevant
dictionary key to keep the count.

Page 11 of 12
Lab Experiment | 11

Rubric for Lab Assessment

The student performance for the assigned task during the lab session was:
The student completed assigned tasks without any help from the
Excellent 4
instructor and showed the results appropriately.
The student completed assigned tasks with minimal help from the
Good 3
instructor and showed the results appropriately.
The student could not complete all assigned tasks and showed
Average 2
partial results.
Worst The student did not complete assigned tasks. 1

Instructor Signature: ______________________________ Date: ____________________

Page 12 of 12

You might also like