Sunteți pe pagina 1din 56

Programming 1

Lecture 10 & 11
Introduction to DATA TYPES
Lecturers
 Karlene Black - UTech
 Euton Gordon – KCC
 Lavre Henry – UTech
 Nathasa Higgin-Thomas - UTech/MCC
 Ian McGowan - UTech
 Courtney McTavish - UTech
 Arleen Penrose – Whittaker - UTech
 Natalee Nembhard - Moneague
 Devon Stoddart - UTech
 KenrayanWhittle - UTech

2
Objectives
 At the end of this lecture you should be able to:
 Make analogy between the generic term array and List in
Python
 Manipulate lists in Python
 Create Parallel Lists
INTRODUCTION
 Variables are a good way to store values in memory, but they
have one limitation – they can hold only one value at a time.
There are many cases, however, where a program needs to
keep a large amount of data in memory and variables are not
the best choice – we solve this problems with the use of data
structures. One type of data structure is arrays
Arrays
 Collection of values with identical properties – similar type
& size
 Similar name for all members, individual element
distinguished by its index / subscript

 Indexing traditionally starts at 0

 An n-element array has members which number


from 0 to n -1.
Defining Arrays – Pseudocode

DECLARE array_name [size] AS data_type

E.g.
DECLARE list[5] AS INTEGER

0 1 2 3 4 (index/subscript)

list 1 2 7 -4 10
(array name)
(array elements)
Arrays – Adding elements
Assigning Data Elements
Array_name[index] = element (element must be of the appropriate type)

EXAMPLE
list[0] = 1
list[1] = 2
list[2]= 7
list[3]= -4
list[4] = 10
Array Positioning
0 1 2 3 4 (index/subscript)

list 1 2 7 -4 10
(array name) An array element is one
value in an array. An
(array elements) array index is an
integer indicating a
position in an array.

Common error:
Very often students confuse the element at the position with
the position itself.
In pseudocode list[3] is -4. It is the element at position 4.
This does not tell what
is stored in the array
but rather it is only
referencing the
subscript in the array!
Array Positioning
0 1 2 3 4 (index/subscript)

list 1 2 7 -4 10
(array name)
(array elements)
Questions:
 What is the line of pseudocode that would display the first
element?
 What is the line of pseudocode that would display the fifth
element?
 How would you refer to the location where 7 is stored?
 How would you write a line of pseudocode to increase the first
value stored in the array by 5?
Array Positioning
0 1 2 3 4 (index/subscript)

list 1 2 7 -4 10
(array name)
(array elements)
Questions:
 What is the line of pseudocode that would display the first
element? list[0]
 What is the line of pseudocode that would display the fifth
element? list[4]
 How would you refer to the location where 7 is stored? list[2]
 How would you write a line of pseudocode to increase the first
value stored in the array by 5? list[0] = list[0] + 5
Initializing an Array
0 1 2 3 4 (index/subscript)

list 0 0 0 0 0
(array name)
(array elements)

Questions:
 Without using a FOR loop, how could you initialize all the
values in the array to 0?

 Using a FOR loop, initialize all the array locations to 0.


Initializing an Array
0 1 2 3 4 (index/subscript)

list 0 0 0 0 0
(array name)
(array elements)
Questions:
 Without using a FOR loop, how could you initialize all the values
in the array to 0?
list[0] = 0, list[1] = 0, etc.
 Using a FOR loop, initialize all the array locations to 0.
FOR x = 0 TO 4
list[x] = 0
ENDFOR
Arrays – Integer Expressions
 Arrays can use any integer expression as its index in the square
brackets.
 Given the values in the array below, what would be the result of the
following?
 list[3 – 2]
 list[0 / 2]
 list[4] / 5

0 1 2 3 4 (index/subscript)

list -20 2 7 -4 10
(array name)
(array elements)
Arrays in PYTHON
Introduction
 There are four collection data types in the Python
programming language:
 List is a collection which is ordered and changeable. Allows
duplicate members.
 Tuple is a collection which is ordered and unchangeable.
Allows duplicate members.
 Set is a collection which is unordered and unindexed. No
duplicate members.
 Dictionary is a collection which is unordered, changeable and
indexed. No duplicate members.
Introduction
 When choosing a collection type, it is useful to understand
the properties of that type. Choosing the right type for a
particular data set could mean retention of meaning, and, it
could mean an increase in efficiency or security.

 Because of time constraints we will focus on LISTS


Creating a Lists
 In Python programming, a list is created by placing all the
items (elements) inside a square bracket [ ], separated by
commas.
 It can have any number of items and they may be of different
types (integer, float, string etc.).
Creating a Lists Cont’d…

1. # empty list
2. my_list = []
3.
4. # list of integers
5. my_list = [1, 2, 3]
6.
7. # list with mixed datatypes
8. my_list = [1, "Hello", 3.4]
Creating a List Cont’d…

Also, a list can even have another list as an item. This is called nested
list.

# nested list

my_list = ["mouse", [8, 4, 6], ['a']]


Creating a List

thislist = ["apple", "banana", "cherry"]


print(thislist)
Accessing Elements From a Lists
 There are various ways in which we can access the elements
of a list.
 List Index
 We can use the index operator [] to access an item in a list.
Index starts from 0. So, a list having 5 elements will have index
from 0 to 4.
 Trying to access an element other that this will raise
an IndexError. The index must be an integer. We can't use float
or other types, this will result into TypeError.
 Nested list are accessed using nested indexing.
Accessing Elements From A List
1. my_list = ['p','r','o','b','e']
2. # Output: p
3. print(my_list[0])
4.
5. # Output: o
6. print(my_list[2])
7.
8. # Output: e
9. print(my_list[4])
10.
11.# Error! Only integer can be used for
indexing
12.# my_list[4.0]
13.
Accessing Elements From a Lists
1. # Nested List
2. n_list = ["Happy", [2,0,1,5]]
3.
4. # Nested indexing
5.
6. # Output: a
7. print(n_list[0][1])
8.
9. # Output: 5
10.print(n_list[1][3])
Negative Indexing
Python allows negative indexing for its sequences. The index of -1
refers to the last item, -2 to the second last item and so on.

1. my_list = ['p','r','o','b','e']
2.
3. # Output: e
4. print(my_list[-1])

5. # Output: p
6. print(my_list[-5])
Negative Indexing
How to Slice Lists In Python
We can access a range of items in a list by using the slicing operator
(colon).

1. my_list = ['p','r','o','g','r','a','m','i','z']
2. # elements 3rd to 5th
3. print(my_list[2:5])
4.
5. # elements beginning to 4th
6. print(my_list[:-5])
7.
8. # elements 6th to end
9. print(my_list[5:])
10.
11. # elements beginning to end
12. print(my_list[:])
How to Change or Add Elements to
a List
List are mutable, meaning, their elements can be
changed. We can use assignment operator (=) to change
an item or a range of items.
1. # mistake values
2. odd = [2, 4, 6, 8]
3. # change the 1st item
4. odd[0] = 1
5. # Output: [1, 4, 6, 8]
6. print(odd)
7. # change 2nd to 4th items
8. odd[1:4] = [3, 5, 7]
9. # Output: [1, 3, 5, 7]
10.print(odd)
Deleting Elements from a List
1. my_list = ['p','r','o','b','l','e','m']
2. # delete one item
3. del my_list[2]
4. # Output: ['p', 'r', 'b', 'l', 'e', 'm']
5. print(my_list)
6. # delete multiple items
7. del my_list[1:5]
8. # Output: ['p', 'm']
9. print(my_list)
10.# delete entire list
11.del my_list
12.# Error: List not defined
13.print(my_list)
Deleting Elements from a Lists
Cont’d…
 We can use remove() method to remove the given item
or pop() method to remove an item at the given index.
 The pop() method removes and returns the last item if index
is not provided. This helps us implement lists as stacks (first
in, last out data structure).
 We can also use the clear() method to empty a list.
Deleting Elements From a List
1. my_list = ['p','r','o','b','l','e','m']
2. my_list.remove('p')
3. # Output: ['r', 'o', 'b', 'l', 'e', 'm']
4. print(my_list)
5. # Output: 'o'
6. print(my_list.pop(1))
7. # Output: ['r', 'b', 'l', 'e', 'm']
8. print(my_list)
9. # Output: 'm'
10.print(my_list.pop())
11.# Output: ['r', 'b', 'l', 'e']
12.print(my_list)
13.my_list.clear()
14.# Output: []
15.print(my_list)
Deleting Elements from a List
we can also delete items in a list by assigning an empty list to a slice of
elements.
Looping Through a Lists
Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
Populating a List with the input
Statement
What is the difference between the
code below and the previous one?
PYTHON Lists Methods
append() - Add an element to the end of the list
extend() - Add all elements of a list to the another list
insert() - Insert an item at the defined index
remove() - Removes an item from the list
pop() - Removes and returns an element at the given index
clear() - Removes all items from the list
index() - Returns the index of the first matched item
S

PYTHON Lists Methods

count() - Returns the count of number of items passed as an argument


sort() - Sort items in a list in ascending order
reverse() - Reverse the order of items in the list
copy() - Returns a shallow copy of the list
Examples of PYTHON Lists
Methods
1. my_list = [3, 8, 1, 6, 0, 8, 4]
2. # Output: 1
3. print(my_list.index(8))
4.
5. # Output: 2
6. print(my_list.count(8))
7.
8. my_list.sort()
9.
10.# Output: [0, 1, 3, 4, 6, 8, 8]
11.print(my_list)
12.
13.my_list.reverse()
14.
15.# Output: [8, 8, 6, 4, 3, 1, 0]
16.print(my_list)
Other Examples
Example 11.1 – Lists (Arrays) &
Loops
 Write a program that prompts the user to enter 10 integers.
The program should then store these elements in an array
and then print them back for the user.
Output
Modify the loop version to also print the square and the cube of
the numbers entered.
Output
Example 11.2
 Use the array declared in Example 11.1 to do the following:
 Search for the number 10 and output whether it has been found
in the array
 Check to see how many even numbers are in the array. Output
this number.
What is the following Code doing?
Output 11.2 Ten Found!!
Output 11.2 – Ten not Found
Parallel Lists
Parallel Lists
 This is a technique for using lists which goes back to the early
days of programming
 It’s not new syntax, just a slightly different way to look at
arrays
 Many languages have a restriction that an array can be only
one type, an integer array, a string array, etc.
Parallel Lists Cont’d…
 Sometimes the situation required storing both floats and
strings, for example (GPAs and names).
 One piece of data, a GPA, belongs with another piece of data,
a name.
 Since they could not be put in the same array, they were put
in separate arrays, but in the same position.
Parallel Lists (Arrays)
 By using the same subscript for both arrays, you are referring
to related data.
 The main thing to remember is if you move data around in
one of the arrays, you must make the same moves in the
other array
 Nothing in the language enforces this relationship, it’s up to
your programming
Parallel Lists (Arrays)
Example:
Example 11.3
 Write a program that will print accept and print the
employee names and the number of shoes sold by six
employees.
Paralell Lists
Output
Sample Output (example 11.4)
ID: 101
Sales: 10

ID: 204
Sales:9

ID: 230
Sales: 2

ID: 232
Sales: 14

ID: 210
Sales: 12

ID: 170
Sales: 6
main()
{
int emp_id [6]; Parallel arrays (same
number of elements, each
int sales_count[6];
element in one array
int i, j; corresponding to an
element in the other array)
for (i=0; i < 6; i++)
are useful for this purpose.
{
printf(“Please enter employee id: “);
emp_id sales_count
scanf(“%d”, &emp_id[i]);
printf(“Please enter sales count: “); 101 10
scanf(“%d”, &sales_count[i]); 204 9
}
230 2
for (i=0; i <6; i++) 232 14
{ 210 12
printf(“%d”, emp_id[i]);
170 6
for (j = 0; j < sales_count[i]; j++)
{
printf(“*”);
}
printf(“\n”);
}
}//end main

S-ar putea să vă placă și