Lists in Python.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Introduction to C Programming
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
One Dimensional Arrays
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Chapter 10 Introduction to Arrays
Lists Introduction to Computing Science and Programming I.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
Chapter 9: Arrays and Strings
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Chapter 9 Introduction to Arrays
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
COMPUTER SCIENCE FEBRUARY 2011 Lists in Python. Introduction to Lists Lists (aka arrays): an ordered set of elements  A compound data type, like strings.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Chapter 8 Arrays and Strings
Session 7 JavaScript/Jscript: Arrays Matakuliah: M0114/Web Based Programming Tahun: 2005 Versi: 5.
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Arrays (Lists) in Python
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Built-in Data Structures in Python An Introduction.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
Lists CS303E: Elements of Computers and Programming.
Lists in Python Selection Sort Algorithm. Sorting A very common activity for computers Not just in business, sorting is used in databases, graphics, simulations,
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Data Collections CS 127. Lists Lists are ordered sequences of items All programming languages provide a sequence structure similar to a Python list; in.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Python Programing: An Introduction to Computer Science
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Lists in Python List methods and functions. List methods MethodSemantics list.append(x)Adds x to the right end of list, changes original list list.sort()Sorts.
Lists in Python Lists as Arguments/Parameters. Lists as arguments to functions Just like other data types, lists can be sent to functions as arguments.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
String and Lists Dr. José M. Reyes Álamo.
List Algorithms Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Computer Programming BCT 1113
Two-dimensional arrays
Containers and Lists CIS 40 – Introduction to Programming in Python
Lists in Python Parallel lists.
JavaScript: Functions.
Lists Part 1 Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Lists Part 1 Taken from notes by Dr. Neil Moore
List Algorithms Taken from notes by Dr. Neil Moore
Bryan Burlingame 03 October 2018
Lists in Python.
String and Lists Dr. José M. Reyes Álamo.
Lists in Python Creating lists.
Lists in Python Outputting lists.
Topics Sequences Introduction to Lists List Slicing
Lists Part 1 Taken from notes by Dr. Neil Moore
For loops Taken from notes by Dr. Neil Moore
CISC101 Reminders Assignment 2 due today.
Topics Sequences Introduction to Lists List Slicing
And now for something completely different . . .
Introduction to Computer Science
Presentation transcript:

Lists in Python

Lists A list is a sequential collection of values, it is a data structure Each value has a location (an index) Indexes range from 0 to n-1 (where n is the length of the list) and from -1 to -n Lists are heterogeneous = values can be of any type (strings are homogeneous because their elements are characters)

List syntax Values are enclosed in [], myList = [3, ‘a’, True] One list can contain another Empty list = [] Any type of data can be in the list You usually refer to a list by elements, that is with the []. You can refer to a list by its name (as one whole thing) when passing it as an argument to a function.

List semantics Lists are mutable, that is, elements can be changed Individual elements can be changed the same way any variable can be changed, with an assignment statement myList = [1,9, ‘a’, 4, 7] m = 3 myList[m] = 99 myList[m+1] = 88

Length function The same as with the string type, len (lst) will return an integer, the number of elements in the list, from zero up to some max int value If a list contains a sublist, it counts as one element L = [1, [3, 4], 7] has 3 elements You call it as part of another statement, for example, print(len(mylist))

Accessing elements of a list The index starts at 0 just like with a string and goes up to n-1 if there are n elements in the list They also can use negative subscripts, -1 is the last element on the right, -n on the left end

Lists in Python Creating lists

Simple ways to create a list Hard code the values mylist = [3, 9, ‘a’, 7.2] Using the replication operator mylist = [0] * 100 (gives a list with 100 zeros) Use the split method on a string Use the readlines method on a file Put [] around a variable if my_num is 5, then [ my_num] is the list [5]

Append vs. Concatenate Both can be used to add to an existing list but their syntax is not the same The concatenate operator + uses two lists and creates a bigger one You cannot say mylist = mylist + “joe”, it must be mylist = mylist + [“joe”] Append is a method which adds an element to the right end of a list – any type of data mylist.append(“3”) makes mylist one element longer

List accumulation Either concatenation or append can be used with lists as accumulators Initialize the list variable as an empty list [] inside your loop either concatenate or append the new item onto your list variable

How to output a list Very simplest way – just print the name of the list print(myList) This results in output that has [] around it, quotes around strings and commas between items More often, the output needs each item without the formatting around it In this case, you need a loop that will process through the list, one element at a time see “Traversing a list” You need either a for loop that presents elements one at a time or a loop that provides the subscript for each element one at a time.

List methods and functions Lists in Python List methods and functions

List methods list.append(x) Semantics list.append(x) Adds x to the right end of list, changes original list list.sort() Sorts items of list, in place. Items must be comparable list.reverse() Reverses order of items in list in place list.index(x) Returns integer index of first (leftmost) occurrence of x list.count(x) Returns integer count of number of occurrences of x in list

Notes about methods These methods, append, sort, reverse, all change the original list. If you need to retain the original list as well as keep the resulting list, use sorted(listname) and list(reversed(listname)) Just as with strings, index will cause an exception and program crash if its search fails

List functions Function Semantics min (list) Returns the smallest element in the list, items must be comparable max (list) Returns the largest element in the list, items must be comparable sum (list) Returns the arithmetic total of all items in list, items must be numeric sorted (list) Returns a new copy of list in ascending order, items must be comparable reversed (list) Returns an iterator of the list in reverse order (use a list typecast to get the list)

Notes about functions and methods When the previous two tables say “items must be comparable”, it means they must all be of numeric type, or they must all be strings. Mixing them will cause an exception and crash When they say “in place” it means that it will change the original list. For the sum function, items can be integer or float

Sequential and Random access of elements Lists in Python Sequential and Random access of elements

Random vs. Sequential Lists have two ways to be accessed random (direct) sequential Both are useful in their place If you need to access ALL elements of a list (either in order or order doesn’t matter), sequential is the way to go because it is simpler Otherwise you need to access elements randomly

Examples sequential for i in range(5): print(myList[i]) random Note that it is the order of elements accessed that makes it sequential or random, both will use the []

Lists as Arguments/Parameters Lists in Python Lists as Arguments/Parameters

Lists as arguments to functions Just like other data types, lists can be sent to functions as arguments The function must be aware of the fact that a parameter is a list, so it can treat it as a list (use subscripts) Lists are passed to functions in a different way than other arguments you have seen so far

Passed by value The process y ou have seen so far is that the values of arguments are copied into the spaces reserved for parameters The function can do anything you want with the copies The copies are deleted when the function finishes and returns This is called ‘passing arguments by value’

Passing by reference Lists are handled differently Their address is sent to the function in the place of a parameter Using the address (also called the reference) the function can change the elements of the list – in other words, the function is changing the original contents of the original list In other words, the list contents can be changed permanently

Python versus other languages In languages like C, C++ and Java, passing by reference is fairly common A main reason for this is that those languages can return no more than one value via a return statement If a function needs to return two things, it must use pass by reference to get one of the things back to the calling code

Python vs. other languages Python on the other hand can return many different values through the return statement Typically functions do not need to pass things by reference because of this fact The main thing to be aware of is that a function can change a list, which will affect the calling function’s variable. Most Python programmers would consider doing this a mistake by the programmer. If you do use passing by reference, document it WELL in the header, so that anyone using the function knows that a list argument can be changed!

Selection Sort Algorithm Lists in Python Selection Sort Algorithm

Sorting A very common activity for computers Not just in business, sorting is used in databases, graphics, simulations, games, etc. Many different algorithms for sorting different ones are better for sorting data in different formats, environments, conditions Python has a sort algorithm builtin, for lists

So why learn a sort algorithm? Good exercise for manipulating lists Not all languages have one builtin Why selection sort? one of the simpler algorithms easy to debug if necessary

Selection sort for n elements (ascending) for n-1 passes find the largest value in unsorted part of list swap it with the value at the end of the unsorted part There are variations based on using smallest instead of largest, on descending instead of ascending

Lists in Python 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.

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 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

Two-dimensional arrays Lists in Python Two-dimensional arrays

Two dimensions You will sometimes have data which has a two-dimensional structure (days and hours for example, or rows and columns) You could store the data in one big list and keep track of the structure some other way but most modern languages provide a way to express the two dimensions directly

List of lists In Python you can think of this structure as a list of lists mat = [[1,2,3], [5, 9, 2], [7, 8, 3], [6, 7, 0]] Of course in Python any of these lists can be any size (they don’t all have to be 3 elements long!) Typically a 2-d array is thought of as having so many rows and so many columns (a grid like Excel)

Syntax of 2-d arrays One way to create a 2-d array is as given on the last slide, just write it out Another that is quicker if you want to initialize all elements to one value: mat2 = [[0] * 3 for i in range(4)] creates a 2-d array with 4 rows, 3 columns full of zeros O

Accessing elements of a 2-d array You use two subscripts, each in a pair of [] mat [2][1] is the element in the third row and second column – just like 1-d arrays, they start numbering at [0][0]