Introduction to Python Lists Arrays or Lists v

  • Slides: 17
Download presentation
Introduction to Python Lists

Introduction to Python Lists

Arrays or Lists v An array is a data structure that allows you to

Arrays or Lists v An array is a data structure that allows you to hold many items of Introduction to name. Python data, all of the same datatype with one v In python Arrays are called Lists, where each element can be a different datatype v An list of 10 student names could be stored in a list: v In most programming languages the “index” starts at 0: § User. Name[0], User. Name[1], …. User. Name[9] v The elements of the array are typically referred to as § User. Name[1], User. Name[2], …. User. Name[10]

Advantages of using Lists v Imagine that you want to input, sort and print

Advantages of using Lists v Imagine that you want to input, sort and print 100 user names. It Python variable names would be very inconvenient. Introduction to use 100 todifferent v With a list you can have as many data items as you need stored using one variable name v Using an array, you can write: FOR number = 1 TO 100 User. Name[number] = USERINPUT(“ Enter a user name”) NEXT number (Sort the names) FOR number = 1 TO 100 Print (User. Name[number]) Next number

Things to Remember v Programmers count from ZERO! Introduction to Python v The first

Things to Remember v Programmers count from ZERO! Introduction to Python v The first item in a list is therefore at position ‘ 0’ v Setting up an empty list: Lists always use square brackets v Adding a variable or literal to a list: v To count the number of items in a list use the len() function eg Setting up a list of strings when the list is initialised

List Manipulation Once a list has been created, there are lots of ways to

List Manipulation Once a list has been created, there are lots of ways to process them: v Print lists Introduction to Python v Append the list (add items on to the end) v Insert items into a particular position of the list For examples of how to add data to a list check out these examples: http: //www. ict 4 u. net/Python/Tryouts/array. Append. php v v v Remove items from the list Remove an item form the end (“Pop” an item out) of the list. Find the index position of an item in the list Sort the list into alphabetical order or numerical order (if the datatype is a number) Reverse the order of the list Count how many times a particular item appears in the list Find example code @ http: //www. ict 4 u. net/Python/Lists. php

Getting Started Creating a List 1. Create new Python file called List Starter. py

Getting Started Creating a List 1. Create new Python file called List Starter. py 2. Save it to your coding folder 3. Goto: http: //www. ict 4 u. net/Python/Tryouts/List. Starter. php 4. The code isn’t complete. Introduction to Python 1. Ask the user to input another fruit 2. Use the append method to add it to the list 3. Print out the list with the new fruit added 4. Can you change this code to use a loop so that the user can enter the names of any fruits they wish Deleting Data From a List 1. Create new Python file called List Remove. py 2. Save it to your coding folder 3. Goto: http: //www. ict 4 u. net/Python/Tryouts/list. REmove. Data. php 4. Copy the code from the webpage into your Python editor 5. Examine the code, run it, make sure that you know how it works. Appending data to a list: http: //www. ict 4 u. net/Python/Tryouts/array. Append. php Finding data in a list: http: //www. ict 4 u. net/Python/Tryouts/List. Find. Count. php Re-ordering, sorting, randomizing etc: http: //www. ict 4 u. net/Python/Tryouts/list. Methods. php

Exercises 1 Make a new file for each task even if you are re-using

Exercises 1 Make a new file for each task even if you are re-using the code. The name for each exercise is in brackets on the first line of the task 1. Introduction The user enters 10 numbers, each number being stored to in a. Python list. (save as Largest Number) Find the largest number print the list using formatted output print the largest number Get the starter code from here: http: //www. ict 4 u. net/Python/Tryouts/List. Largest. Number. php 2. The user enters 10 numbers each number being stored in a list. (save as Descending Numbers) Order the list from largest to smallest print the list using formatted output (see above example) 3. Generate a list of 100 random numbers and store them in a list. Use a for loop to go through the list finding the minimum and maximum values. Print the results using formatted output (save as Max and Min)

Exercises 2 1. The user enters 10 names each being stored in a list.

Exercises 2 1. The user enters 10 names each being stored in a list. Reverse the order of the list print the list using formatted output 2. (save as Names Reversed) Introduction to Python Using the names list from the previous exercise (save as Find a Name) Prompt the user for a name to find Count how many times the name appears in the list. Display the name and the number of times it was found 3. Using the name list from the previous exercise (save as Position in List) Prompt the user for a name If the name is in the list display the name and the index position otherwise display the name and a message that it was not in the list 4. Using the name list from the previous exercise. (save as Remove a Name) print the list using formatted output Remove the 0 and 4 th items. After each item has been removed, print the list using formatted output and the current length of the list Prompt the user for a name and then remove it from the list print the list using formatted output and the current length of the list 5. Copy the starter code from this link: https: //bit. ly/2 ML 7 VPH (save as Strings and Numbers) Use the hints in the code to create separate lists of strings and numbers. Sort the strings list in ascending order – print the results using formatted output Sort the strings list in descending order - print the results using formatted output Choose one item at random from the list of strings and print it out Sort the number list from lowest to highest - print the results using formatted output Sort the number list from highest to lowest - print the results using formatted output Randomise the list of numbers. print the results using formatted output

Exercises 3 1. Adam wants to record the goals scored by his favourite football

Exercises 3 1. Adam wants to record the goals scored by his favourite football team. (save as Football Team) Create a python program that starts with an empty list and allows him to enter as many scores until -1 is entered Print all the entries recorded in a formatted manner Introduction to Python 2. Adam wants to know how well his team is doing. (save as Football Analysis) Modify the Fooball Team program to count all the numbers in the list, sum their values and work out the average. After all the scores have been printed also show the number of goals scored (count) total goals (sum) and average print the list using formatted manner and the current length of the list 3. Things are going well. Adam wants to compare this season with last Compare) (save as Football Last season Adam’s recorded the following goal scores for his team: 4, 2, 5, 1, 5, 3, 2, 7 Modify your program so that it starts with last season’s scores already stored in one list When this seasons scores have been entered merge the two list and sort them into ascending order. Print the results in a formatted manner as for the previous task

Exercises 3 - Continued 4. Joe is a film fanatic He wants to keeps

Exercises 3 - Continued 4. Joe is a film fanatic He wants to keeps a list of the top 12 movies taking the most revenue at the box office. (save as Best Introduction to Python Movies) Click here to open a python file to This is a rolling list meaning that when the list is full the oldest movie (at the end of the list) is discarded to make way for the new movie at the beginning. Open this link for starter code: https: //bit. ly/2 HLNm. Ux For example Column A shows the full list before a new item is added Column B show the revised list after a new movie Cars 3 has been added Write a program to allow Joe to add a new movie to the list Print the list in a formatted manner showing Column A Column B the position in the list and the title of the movie 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 Minions Star Wars: The Force Awakens Jurassic World Avengers Inside Out Furious 7 The Hunger Games: Mockingjay The Martian Cinderella Spectre Pirates Of The Caribbean: Beauty And The Beast Spider-Man: Homecoming 1 Star Wars: The Force Awakens 2 Jurassic World 3 Avengers Inside Out 4 Furious 7 5 The Hunger Games: Mockingjay 6 The Martian 7 8 9 Cinderella Spectre Pirates Of The Caribbean: 10 Beauty And The Beast 11 Spider-Man: Homecoming 12 Cars 3

Printing a List in Python Introduction to Python The whole list is printed without

Printing a List in Python Introduction to Python The whole list is printed without any formatting Use a for loop to iterate through the list Then each item can be formatted in the output

2 D Lists – part 1 v Two dimensional array is an array within

2 D Lists – part 1 v Two dimensional array is an array within an array. Introduction to Python v In this type of array the position of a data element is referred by two indices instead of one. v You can use 2 D arrays for storing tables or large amounts of data. v For example, we have a list of people. We also have their: favourite number, favourite colour and favourite fruit. Name Age Favourite Colour Favourite Fruit Scarecrow 10 Blue Strawberry Tin Man 15 Green Apple Lion 13 White Blueberries Dorothy 12 Yellow Banana

2 D Lists – part 2 There are three ways of storing this: 1.

2 D Lists – part 2 There are three ways of storing this: 1. Introduction Using a different variables for piece of data: to Python first. Name = ‘Scarecrow’ first. Fav. Number = 10 first. Colour = ‘Blue’ first. Fruit = ‘Strawberry’ second. Name = ‘Tin Man’ second. Fav. Number = 15 etc This is not satisfactory as it takes a long time to type out each variable, is difficult to process and can be confusing at times. 2. Using Single List for each person e. g. in the order of name, favourite number, favourite colour, favourite fruit first = [‘Scarecrow’, 10, ‘Blue’, ‘Strawberry’] second = [‘Tin Man’, 15, ‘Green’, ‘Apple’] etc This is also not a preferred method. The data can get confusing, and it is difficult to add data for another person. It is still difficult to process.

2 D Lists – part 3 2. Merge all of single array lists into

2 D Lists – part 3 2. Merge all of single array lists into one big 2 D array list. In the order of name, favourite number, favourite to colour, favourite fruit: Introduction Python list. Favorites = [ [Scarecrow', 10, 'Blue', 'Strawberry'], [Tin Man', 15, 'Green', 'Apple'], [Lion', 13, 'White', 'Blueberries'], ['Dorothy', 12, 'Yellow', 'Banana'] ] v To pick a value from the 2 d array, reference it with two square brackets. v In the first, you enter the ‘record’, in the second you enter the ‘field’ of the larger list. v For example, the favourite colour of the second entry: print(list. Favourites[1][2]) will return Green, Tin Man’s favourite colour.

Scenario A teacher is keeping track of GCSE students for a group of students

Scenario A teacher is keeping track of GCSE students for a group of students Introduction to Python He is monitoring progress over 4 key subjects: English Maths Science Geography The data is stored in a Python program He needs some help in being able to modify and analyse the data The exercises on the following slides tell you exactly what he requires

Exercises 4 – Modify, Create, Delete 1. Create a new python file (save as

Exercises 4 – Modify, Create, Delete 1. Create a new python file (save as Student Results) Copy the code stub from this link: https: //bit. ly/2 DOHcy. M Sort the data on student last name Introduction to: Python Print the data so that it is formatted to match this as closely as you can 2. Some of the data is incorrect (save as Student Results Update) Miranda Lake achieved a score of 58 in Maths Kamron Potter scored 63 in Science Write some code to change these values. As an extension allow the user to choose the student and subject whose scores need to be changed. Print the details of all the class in a similar format to task 1 3. Some of the data is missing (save as Student Results Add) The details for Grace Cherry are missing and need to be added Write some code to insert these values As an extension allow the user to choose the student and subject whose scores need to be added. Print the details of all the class in a similar format to task 1 4. Some of the data is redundant Name Cherry, Grac e Ma En Sc Ge 43 40 90 88 (save as Student Results Delete) Deegan Walton has left the school and his scores are no longer required. Write some code to remove his details As an extension allow the user to choose the student and subject whose scores need to be removed. Print the details of all the class in a similar format to task 1

Exercises 5 – Analysing data Note: These tasks are still working with the Student

Exercises 5 – Analysing data Note: These tasks are still working with the Student data from Exercises 3 1. Best Overall Student (save as Student Best Overall ) 2. Best Grades in each subject (save as Student best subject) The teacher wants to know who is doing best in all 4 subjects Introduction to Python Add the scores for all four subjects, store in a new field called Total Print the name of the student, subject scores and total OR Sort the data on the overall column and print it out, stating clearly the order the data is printed in. Check out this link: https: //bit. ly/2 Tr 46 Sg which demonstrates how to sort a nested list The teacher wants to know for each subject, the Maximum score, Minimum Score and the Average score Your output should look something like this There a number of ways to do this: • Calculate the max and min for all subject by storing the results in another list • Store the results in separate variables