SlideShare a Scribd company logo
Page 1


6.189 – Notes/Homework
Session 6

Administrivia
Name:



Instructions:
1. Err..complete the questions :). Putting a serious effort into this homework is mandatory for receiving
a passing grade in this course (note the word effort – getting them all wrong is ok, but skipping this
homework is not.)
2. These notes (and homework problems) are a continuation of the notes from Exam 1.
3. Some problems may be marked {alone} (it’ll be in red and braces.) Work on those problems alone!
4. When we ask for output, you DON'T have to write the spaces/newlines in.
    Program Text:

      print “X”,
      print “X”,


    Output:



                                                   XX
Day 4: List Basics
Notes:
This section covers the basics of lists. We'll cover them in more detail after we cover objects and
references.

We've used variables to store basic information such as numbers, strings, and boolean values. We can
also store more complex information. A list stores a sequence of elements [x1,x2,x3,...]. Note that
order matters: [x1,x2] != [x2,x1]

You can store different types of variables in the same list: [1,3,"test",True]. You can even store
lists in lists! (Note: For now, don't store lists in lists! You'll understand why when we talk about objects
and mutability.)

Chapters 9.1-9.3 cover basic syntax on using lists. Here’s a quick review:

  - You can create a list using square brackets [1,2,5,1,3,"test"].
  - To read an element from list some_list, use some_list[index]. The index of an element is just
    its position, but note that the first element is considered to have a position of 0!
Page 2


  - The built-in function len(x) will find the length of any list passed in as a parameter. This works
    more generally with any complex data structure (like dictionaries, which we'll cover later) as well as
    strings.

We'll also be using the following syntax for adding something to the end of a list.

    Program Text:

      some_list = [1,2,3,4]
      some_list.append(5)
      print some_list

    Output:

      [1,2,3,4,5]


For now, just memorize the syntax -- you'll understand what's going on in a later section.

Problem 12 {alone}:
What is the output of the following code. The output of each program has at most two semi-colons.

    Program Text:

      some_list = [3,6,2,5]
      i = 1
      while i < 3:
        print some_list[i], ";"
        i = i + 1
      print some_list[3]

    Output:




    Program Text:

      list1 = [2,5,6,3,7,8,12]
      list2 = [1,2,6,5,7,3,12]
      i = 0
      while i < 6:
        if list1[i] == list2[i]:
          print list1[i], ";",
        i = i + 1
      print len(list1)

    Output:
Page 3


Day 6: Objects and References
Notes:
Lists are fundamentally different than everything we've seen to date. They are the first example we've
seen of an object.

You've learned that we can use variables to store information in a table. This works for simple things like
numbers, but not for complex information like a list. Instead, Python stores this information in an area
of memory called the heap.

Understanding what the heap is isn't important. What is important to know, however, is that instead of
storing objects in the variable table, Python stores a pointer or reference to the object.

A reference is like an arrow. The easiest way to explain this is with an example:

    Program Text:

      example_list = []

      def append_one(my_list):
        "This is a function that adds something to the end of a list"
        #Point 2
        my_list.append(1)
        #Point 3

      #Point 1
      append_one(example_list)
      print example_list
      #Point 4

    Output:

      [1]


At point 1, the variable table looks something like the following.




After this, we pass the location of the list (which is the value stored in the variable) to the function. Thus,
at point 2 both variables point to the same thing.
Page 4




We change the list afterwards, and the table looks like the following at point 3.




The local variable disappears when the function ends, and at point 4 the variable table looks like the
following.




Hence the output of the code is [1]! This differs from problem 10 – since these variables are storing
arrows, any changes we make within the function are reflected outside of it too.

This arrow is literally stored as an integer in the table – think of it as a locker number. We can find out
the value of this number using the id(x) function.
Page 5


    Program Text:

      def small_function(my_list):
        print "in function:"
        print id(my_list)
        my_list.append(1)

      example_list = []
      example2_list = [3,6]
      print id(example_list)
      print id(example2_list)

      small_function(example_list)

    Output:

      18162752
      12860152
      in function:
      18162752


Note: Your numbers may differ from mine. The first and last numbers will still be the same, though.

You probably won't need to use the id function ever. Its really useful for figuring out whether two
variables are pointing to the same list or not, though.

Problem 13:
What is the output of the following code. Use single digits for the output of id(x).

    Program Text:

      some_list = [1,3,2]

      def f1(my_list):
        new_list = [2]
        print id(my_list), "; ",
        print id(new_list), ";",

      print id(some_list), "; ",
      f1(some_list)

    Output:
Page 6


    Program Text:

      some_list = [1,3,2]

      def f1(my_list)
        my_list.append(7)
        print id(my_list), “;”,
        return [1,4,5]

      print id(some_list), “;”,
      some_list.append(5)
      print id(some_list), “;”,
      some_list = [4,3,7]
      print id(some_list), “;”,
      some_list = f1(some_list)
      print id(some_list)

    Output:




Day 6: Mutability
Notes:
Now that you understand the true nature of a list, we can talk about the concept of mutability. Lists are
an example of a mutable object. Mutability is a synonym for changable – in essence, we're saying that
you can change a list. Be careful -- while this sounds very simple, it can get quite tricky.

For the next problem, the references example will help a lot. Remember that statements like list1 =
[1,2,5] change the reference (what the arrow is pointing to) and statements like list1.append(5)
change the list itself.

Problem 14:
What is the output of the following code.

    Program Text:

      list1 = [1,2,4]
      list2 = list1
      list2.append(3)
      print list1

    Output:
Page 7


Program Text:

  list1 = [1,2,4]
  list2 = [1,2,4]
  list2.append(3)
  print list1

Output:




Program Text:

  example_list = [1,2,4]

  def f1(my_list):
    my_list.append(3)

  f1(example_list)
  print example_list

Output:




Program Text:

  example_list = [1,2,4]

  def f1(my_list):
    my_list = [1,2,4,3]

  f1(example_list)
  print example_list

Output:
Page 8


    Program Text:

      list1 = [1,2,4]
      list2 = [1,2,4]
      list3 = list2
      list2.append(3)
      list2 = list1
      list2.append(3)
      list1.append(3)
      list1 = list3
      print list1, ";",
      print list3

    Output:




We’ll talk about immutable objects later when we cover tuples and revisit strings.

Day 6: Member functions
Notes:
We saw at the append function earlier – this function had some unusual syntax. Objects have something
called member functions. append is a member function of a list.

In essence, member functions are basically shorthand. Python could easily have made a general
append(some_list, element) function that appends the value of element to the list some_list.
Instead, we use the member function of some_list: we write some_list.append(element) to
append an element to some_list.

In general, member functions have the syntax object_name.function(parameters) – the function
affects or applies to the object object_name.

Day 4: Lists Redux
Notes:
Now let's go over lists for real. Remember what you've just learned about them.

  - Lists are mutable objects. When you change a list somewhere, every other reference will still point
    to the now changed list.
  - Lists have member functions. For lists, these functions tend to change the list itself.

Basics: You already know how to create a list and read its members. You can also use the
example_list[i] syntax to change values, e.g. example_list[1] = 5. Finally, you can write del
example_list[i] to delete the element at position i.

Length: As mentioned earlier, you can use the built-in function len(x) to find the length of a list.
Page 9


Membership: The in operator can be used to determine whether an element is a member of a list or
not. 3 in [3,5,7] evaluates to True, while 6 in [3,4,1] evaluates to false.

Analogous to !=, you can use not in to check if an element is NOT a member of a list. 12 not in
[3,5,7] returns True.

Warning: Never use booleans for this operator unless the list consists ONLY of booleans. Recall that the
== operator can compare different types; Python considers 0 == False and any other number equal to
True. Hence, True in [0,3,5] evaluates to True because 3 == True is considered True by Python.

Member functions: All of the following functions change the list they're called from. They have NO
return values.

  -   append(element). Appends element to the end of the list.
  -   insert(index, element). Inserts element before the list element at index.
  -   reverse(). Reverses the order of elements in the list.
  -   remove(element). Removes the first instance of element from the list.

The following function(s) don’t change the list. They return information about the list instead.

  - index(element). Returns the position of the first instance of element in the list.
  - count(element). Returns the number of times element appears in the list.

Don’t worry too much about memorizing all these functions. Just keep in mind that they exist.

Concatenation: You can combine two lists into a new list with the concatenation operator +.

Problem 15:
Write a definition for the following shift functions. shift takes a list and moves the first element to the
very end. reverse_shift does the opposite – it moves the last element to the beginning of the list.
Neither function should return anything!

      Program Text:

        def shift(my_list):
           "Shifts the list [x1,x2,...,xn] to [x2,x3,...,xn,x1]."
Page 10



    Program Text:

      def reverse_shift(my_list):
         "Shifts the list [x1,x2,...,xn] to [xn,x1,x2,...,x(n-1)]."




Problem 16:
Write a definition for the function last_index. last_index takes a list and an element and returns
the position of the last instance of element in list, e.g. last_index([3,4,3,7,9],3) returns 2. Be
sure that list is in its original form when your function completes! (either create your own copy of the
list or reverse any changes you make.)

    Program Text:

      def last_index(my_list, element):
         "Returns the position of the last instance of element in my_list"




Day 4: Advanced Positioning and Slicing
Notes:
You've already learned about the notation for selecting an element some_list[i] by using its
position. You can also use negative numbers to select an element – the last element is considered to
have position -1.
Page 11


You can do even slicker things. some_list[start:end] creates a list slice – it returns a new list with
all the elements between start and end – 1 from the original list. If you omit either start or end,
it’ll select all elements from the beginning / up until the end, e.g. some_list[1:] creates a slice
including all but the first element.

You can change the values of slices the same way you change individual values, e.g. some_list[3:5]
= [1,5,4,4,7]. Note that the new assignment doesn’t have to be the same length as the list slice you
cut out.

Note, however, that if you assign the slice to a variable, that variable points to a new list.

    Program Text:

      list1 = [1,3,5,7]
      list1[1:3] = [2,4,6]
      print list1
      list2 = list1[1:] #list2 points to a new list
      list2.append(55)
      print list1
      print len(list1)
      list1[3:5] = [8,8,8,8]
      print list1

    Output:

      [1, 2, 4, 6, 7]
      [1, 2, 4, 6, 7]
      5
      [1, 2, 4, 8, 8, 8, 8]


some_list[:] creates a duplicate of the list. This is very useful – since most of our list techniques
destructively change the list, many times, it may be a good idea to create a duplicate of the list and mess
around with that instead.

Problem 17:
What is the output of the following code.

    Program Text:

      list1 = [4,6,12]
      list2 = list1[:]
      list1.append(4)
      print list2

    Output:
Page 12


   Program Text:

     list1 = [2,5,6,3]
     i = 1
     while i < len(list1):
       print list1[-i], ";",
       i = i + 1
     print list1[-len(list1)]

   Output:




   Program Text:

     list1 = [1,2,3]
     i = 1
     while i < len(list1):
       print list1[:i], ";",
       i = i + 1
     print list1

   Output:




Day 4: Range function
Notes:
range(x) is a built-in function that returns a list [0,1,...,x-1], e.g. range(3) returns [0,1,2].
You can also do range(start, finish), which creates the list [start, start+1, ...,
finish-1]. Its a very useful function.

Day 4: For loop
Notes:
Like the while loop, the for loop is another control flow command – a way of executing a sequence of
statements multiple times. A for loop executes a sequence of statements once for each element in a
list.

   Program Text:

     for i in [1,2,4,6]:
       print i, ";",
     print 8

   Output:

     1;2;4;6;8
Page 13


The for loop is incredibly useful. For example, you can combine the for loop and range(x) function
to execute a statement a fixed number of times.

Problem 18:
Write a definition for a function that takes a list and returns the sum of all elements in that list.

    Program Text:

      def sum_elements(my_list):
         "Returns the sum of all elements in my_list"




Day 4: Basic Advanced Loops
Notes:
This title is not a contradiction :p. For loops can be incredibly difficult to use correctly. This section will
give you a bunch of problems to give you practice in solving problems with for loops.

Problem 19:
Each of the following function definitions takes a list as a parameter and solves a specific problem.
Correctly fill the blanks in the following code to solve the problems.

There is a way to solve each problem by only filling in the blanks. Don’t just add extra lines to force a
solution. Also, there may even be more elegant solutions that don’t use all the blanks – feel free to use
those too.

    Program Text:

      def all_under_6(my_list):
        """Returns True if ALL members in my_list are under 6 (False
      otherwise). my_list must be list of integers."""
         under_6 = ___________
         for i in my_list:
             if __________________:
                _________________________________________________________
         return under_6
Page 14


Program Text:

  def no_vowels(my_list):
    """Returns True if my_list contains only consonants (no vowels).
  Assume that my_list only contains lowercase letters."""
     vowels = ['a','e','i','o','u']
     contains_vowels = _________
     for i in __________________:
         if ______________________:
            ____________________________________________________________
     return not contains_vowels

Program Text:

  def find_max_element(my_list):
    """Finds and returns the maximum value contained in my_list.
  Assume my_list contains positive values only."""
     max_value = -1
     for i in __________________:
         if ______________________:
            ____________________________________________________________
     return max_value

More Related Content

What's hot

Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
eShikshak
 
Python list
Python listPython list
Python list
Mohammed Sikander
 
Lists
ListsLists
Python :variable types
Python :variable typesPython :variable types
Python :variable types
S.M. Salaquzzaman
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
Mohammed Sikander
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
Python Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - ListsPython Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - Lists
P3 InfoTech Solutions Pvt. Ltd.
 
Data types in python
Data types in pythonData types in python
Data types in python
RaginiJain21
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
Sujith Kumar
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_python
deepalishinkar1
 
List in Python
List in PythonList in Python
List in Python
Siddique Ibrahim
 
Python : Data Types
Python : Data TypesPython : Data Types
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
Python data type
Python data typePython data type
Python data type
Jaya Kumari
 
1. python
1. python1. python
1. python
PRASHANT OJHA
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)
Pedro Rodrigues
 
Basic data types in python
Basic data types in pythonBasic data types in python
Basic data types in python
sunilchute1
 
Values and Data types in python
Values and Data types in pythonValues and Data types in python
Values and Data types in python
Jothi Thilaga P
 
Python-03| Data types
Python-03| Data typesPython-03| Data types
Python-03| Data types
Mohd Sajjad
 

What's hot (19)

Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
Python list
Python listPython list
Python list
 
Lists
ListsLists
Lists
 
Python :variable types
Python :variable typesPython :variable types
Python :variable types
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Python Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - ListsPython Programming Essentials - M12 - Lists
Python Programming Essentials - M12 - Lists
 
Data types in python
Data types in pythonData types in python
Data types in python
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_python
 
List in Python
List in PythonList in Python
List in Python
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
Python data type
Python data typePython data type
Python data type
 
1. python
1. python1. python
1. python
 
Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)Introduction to the basics of Python programming (part 3)
Introduction to the basics of Python programming (part 3)
 
Basic data types in python
Basic data types in pythonBasic data types in python
Basic data types in python
 
Values and Data types in python
Values and Data types in pythonValues and Data types in python
Values and Data types in python
 
Python-03| Data types
Python-03| Data typesPython-03| Data types
Python-03| Data types
 

Viewers also liked

Does Your Festival or Event MakeCcent$
Does Your Festival or Event MakeCcent$Does Your Festival or Event MakeCcent$
Does Your Festival or Event MakeCcent$
Sarah Page
 
Everywhere Ergonomics
Everywhere ErgonomicsEverywhere Ergonomics
Everywhere Ergonomics
The Economist Media Businesses
 
Talon Financial
Talon FinancialTalon Financial
Talon Financial
sberrios
 
Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 02
Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 02Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 02
Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 02
Sukarya
 

Viewers also liked (7)

Does Your Festival or Event MakeCcent$
Does Your Festival or Event MakeCcent$Does Your Festival or Event MakeCcent$
Does Your Festival or Event MakeCcent$
 
Everywhere Ergonomics
Everywhere ErgonomicsEverywhere Ergonomics
Everywhere Ergonomics
 
Text book
Text bookText book
Text book
 
Talon Financial
Talon FinancialTalon Financial
Talon Financial
 
finalproject
finalprojectfinalproject
finalproject
 
Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 02
Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 02Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 02
Run for Sukarya in the Airtel Delhi Half Marathon 2012 - 02
 
Student kap hiv aids
Student kap hiv aidsStudent kap hiv aids
Student kap hiv aids
 

Similar to pyton Notes6

The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189
Mahmoud Samir Fayed
 
Introduction To Programming with Python-4
Introduction To Programming with Python-4Introduction To Programming with Python-4
Introduction To Programming with Python-4
Syed Farjad Zia Zaidi
 
Although people may be very accustomed to reading and understanding .docx
Although people may be very accustomed to reading and understanding .docxAlthough people may be very accustomed to reading and understanding .docx
Although people may be very accustomed to reading and understanding .docx
milissaccm
 
The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181
Mahmoud Samir Fayed
 
Python - Data Collection
Python - Data CollectionPython - Data Collection
Python - Data Collection
JoseTanJr
 
Python Objects
Python ObjectsPython Objects
Python Objects
MuhammadBakri13
 
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docxAssg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx
festockton
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And Answers
H2Kinfosys
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
Out Cast
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
ssuser8e50d8
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
Asst.prof M.Gokilavani
 
Python advance
Python advancePython advance
Python advance
Deepak Chandella
 
Data structure
 Data structure Data structure
Data structure
Shahariar limon
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
CatherineVania1
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
NehaSpillai1
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
NehaSpillai1
 
Lecture 09.pptx
Lecture 09.pptxLecture 09.pptx
Lecture 09.pptx
Mohammad Hassan
 
The Ring programming language version 1.3 book - Part 13 of 88
The Ring programming language version 1.3 book - Part 13 of 88The Ring programming language version 1.3 book - Part 13 of 88
The Ring programming language version 1.3 book - Part 13 of 88
Mahmoud Samir Fayed
 

Similar to pyton Notes6 (20)

The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189The Ring programming language version 1.6 book - Part 24 of 189
The Ring programming language version 1.6 book - Part 24 of 189
 
Introduction To Programming with Python-4
Introduction To Programming with Python-4Introduction To Programming with Python-4
Introduction To Programming with Python-4
 
Although people may be very accustomed to reading and understanding .docx
Although people may be very accustomed to reading and understanding .docxAlthough people may be very accustomed to reading and understanding .docx
Although people may be very accustomed to reading and understanding .docx
 
The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181The Ring programming language version 1.5.2 book - Part 21 of 181
The Ring programming language version 1.5.2 book - Part 21 of 181
 
Python - Data Collection
Python - Data CollectionPython - Data Collection
Python - Data Collection
 
Python Objects
Python ObjectsPython Objects
Python Objects
 
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docxAssg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docx
 
Python Interview Questions And Answers
Python Interview Questions And AnswersPython Interview Questions And Answers
Python Interview Questions And Answers
 
pyton Notes9
pyton Notes9pyton Notes9
pyton Notes9
 
Python lists
Python listsPython lists
Python lists
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
 
11 Introduction to lists.pptx
11 Introduction to lists.pptx11 Introduction to lists.pptx
11 Introduction to lists.pptx
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
Python advance
Python advancePython advance
Python advance
 
Data structure
 Data structure Data structure
Data structure
 
Improve Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptxImprove Your Edge on Machine Learning - Day 1.pptx
Improve Your Edge on Machine Learning - Day 1.pptx
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
 
Lecture 09.pptx
Lecture 09.pptxLecture 09.pptx
Lecture 09.pptx
 
The Ring programming language version 1.3 book - Part 13 of 88
The Ring programming language version 1.3 book - Part 13 of 88The Ring programming language version 1.3 book - Part 13 of 88
The Ring programming language version 1.3 book - Part 13 of 88
 

More from Amba Research

Case Econ08 Ppt 07
Case Econ08 Ppt 07Case Econ08 Ppt 07
Case Econ08 Ppt 07
Amba Research
 
Case Econ08 Ppt 06
Case Econ08 Ppt 06Case Econ08 Ppt 06
Case Econ08 Ppt 06
Amba Research
 
Case Econ08 Ppt 05
Case Econ08 Ppt 05Case Econ08 Ppt 05
Case Econ08 Ppt 05
Amba Research
 
Case Econ08 Ppt 04
Case Econ08 Ppt 04Case Econ08 Ppt 04
Case Econ08 Ppt 04
Amba Research
 
Case Econ08 Ppt 03
Case Econ08 Ppt 03Case Econ08 Ppt 03
Case Econ08 Ppt 03
Amba Research
 
Case Econ08 Ppt 02
Case Econ08 Ppt 02Case Econ08 Ppt 02
Case Econ08 Ppt 02
Amba Research
 
Case Econ08 Ppt 01
Case Econ08 Ppt 01Case Econ08 Ppt 01
Case Econ08 Ppt 01
Amba Research
 
learn matlab for ease Lec5
learn matlab for ease Lec5learn matlab for ease Lec5
learn matlab for ease Lec5Amba Research
 

More from Amba Research (20)

Case Econ08 Ppt 16
Case Econ08 Ppt 16Case Econ08 Ppt 16
Case Econ08 Ppt 16
 
Case Econ08 Ppt 08
Case Econ08 Ppt 08Case Econ08 Ppt 08
Case Econ08 Ppt 08
 
Case Econ08 Ppt 11
Case Econ08 Ppt 11Case Econ08 Ppt 11
Case Econ08 Ppt 11
 
Case Econ08 Ppt 14
Case Econ08 Ppt 14Case Econ08 Ppt 14
Case Econ08 Ppt 14
 
Case Econ08 Ppt 12
Case Econ08 Ppt 12Case Econ08 Ppt 12
Case Econ08 Ppt 12
 
Case Econ08 Ppt 10
Case Econ08 Ppt 10Case Econ08 Ppt 10
Case Econ08 Ppt 10
 
Case Econ08 Ppt 15
Case Econ08 Ppt 15Case Econ08 Ppt 15
Case Econ08 Ppt 15
 
Case Econ08 Ppt 13
Case Econ08 Ppt 13Case Econ08 Ppt 13
Case Econ08 Ppt 13
 
Case Econ08 Ppt 07
Case Econ08 Ppt 07Case Econ08 Ppt 07
Case Econ08 Ppt 07
 
Case Econ08 Ppt 06
Case Econ08 Ppt 06Case Econ08 Ppt 06
Case Econ08 Ppt 06
 
Case Econ08 Ppt 05
Case Econ08 Ppt 05Case Econ08 Ppt 05
Case Econ08 Ppt 05
 
Case Econ08 Ppt 04
Case Econ08 Ppt 04Case Econ08 Ppt 04
Case Econ08 Ppt 04
 
Case Econ08 Ppt 03
Case Econ08 Ppt 03Case Econ08 Ppt 03
Case Econ08 Ppt 03
 
Case Econ08 Ppt 02
Case Econ08 Ppt 02Case Econ08 Ppt 02
Case Econ08 Ppt 02
 
Case Econ08 Ppt 01
Case Econ08 Ppt 01Case Econ08 Ppt 01
Case Econ08 Ppt 01
 
Notes8
Notes8Notes8
Notes8
 
Notes7
Notes7Notes7
Notes7
 
pyton Notes1
pyton Notes1pyton Notes1
pyton Notes1
 
pyton Exam1 soln
 pyton Exam1 soln pyton Exam1 soln
pyton Exam1 soln
 
learn matlab for ease Lec5
learn matlab for ease Lec5learn matlab for ease Lec5
learn matlab for ease Lec5
 

Recently uploaded

De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
Pierluigi Pugliese
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
ViralQR
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 

Recently uploaded (20)

De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024By Design, not by Accident - Agile Venture Bolzano 2024
By Design, not by Accident - Agile Venture Bolzano 2024
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.Welocme to ViralQR, your best QR code generator.
Welocme to ViralQR, your best QR code generator.
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 

pyton Notes6

  • 1. Page 1 6.189 – Notes/Homework Session 6 Administrivia Name: Instructions: 1. Err..complete the questions :). Putting a serious effort into this homework is mandatory for receiving a passing grade in this course (note the word effort – getting them all wrong is ok, but skipping this homework is not.) 2. These notes (and homework problems) are a continuation of the notes from Exam 1. 3. Some problems may be marked {alone} (it’ll be in red and braces.) Work on those problems alone! 4. When we ask for output, you DON'T have to write the spaces/newlines in. Program Text: print “X”, print “X”, Output: XX Day 4: List Basics Notes: This section covers the basics of lists. We'll cover them in more detail after we cover objects and references. We've used variables to store basic information such as numbers, strings, and boolean values. We can also store more complex information. A list stores a sequence of elements [x1,x2,x3,...]. Note that order matters: [x1,x2] != [x2,x1] You can store different types of variables in the same list: [1,3,"test",True]. You can even store lists in lists! (Note: For now, don't store lists in lists! You'll understand why when we talk about objects and mutability.) Chapters 9.1-9.3 cover basic syntax on using lists. Here’s a quick review: - You can create a list using square brackets [1,2,5,1,3,"test"]. - To read an element from list some_list, use some_list[index]. The index of an element is just its position, but note that the first element is considered to have a position of 0!
  • 2. Page 2 - The built-in function len(x) will find the length of any list passed in as a parameter. This works more generally with any complex data structure (like dictionaries, which we'll cover later) as well as strings. We'll also be using the following syntax for adding something to the end of a list. Program Text: some_list = [1,2,3,4] some_list.append(5) print some_list Output: [1,2,3,4,5] For now, just memorize the syntax -- you'll understand what's going on in a later section. Problem 12 {alone}: What is the output of the following code. The output of each program has at most two semi-colons. Program Text: some_list = [3,6,2,5] i = 1 while i < 3: print some_list[i], ";" i = i + 1 print some_list[3] Output: Program Text: list1 = [2,5,6,3,7,8,12] list2 = [1,2,6,5,7,3,12] i = 0 while i < 6: if list1[i] == list2[i]: print list1[i], ";", i = i + 1 print len(list1) Output:
  • 3. Page 3 Day 6: Objects and References Notes: Lists are fundamentally different than everything we've seen to date. They are the first example we've seen of an object. You've learned that we can use variables to store information in a table. This works for simple things like numbers, but not for complex information like a list. Instead, Python stores this information in an area of memory called the heap. Understanding what the heap is isn't important. What is important to know, however, is that instead of storing objects in the variable table, Python stores a pointer or reference to the object. A reference is like an arrow. The easiest way to explain this is with an example: Program Text: example_list = [] def append_one(my_list): "This is a function that adds something to the end of a list" #Point 2 my_list.append(1) #Point 3 #Point 1 append_one(example_list) print example_list #Point 4 Output: [1] At point 1, the variable table looks something like the following. After this, we pass the location of the list (which is the value stored in the variable) to the function. Thus, at point 2 both variables point to the same thing.
  • 4. Page 4 We change the list afterwards, and the table looks like the following at point 3. The local variable disappears when the function ends, and at point 4 the variable table looks like the following. Hence the output of the code is [1]! This differs from problem 10 – since these variables are storing arrows, any changes we make within the function are reflected outside of it too. This arrow is literally stored as an integer in the table – think of it as a locker number. We can find out the value of this number using the id(x) function.
  • 5. Page 5 Program Text: def small_function(my_list): print "in function:" print id(my_list) my_list.append(1) example_list = [] example2_list = [3,6] print id(example_list) print id(example2_list) small_function(example_list) Output: 18162752 12860152 in function: 18162752 Note: Your numbers may differ from mine. The first and last numbers will still be the same, though. You probably won't need to use the id function ever. Its really useful for figuring out whether two variables are pointing to the same list or not, though. Problem 13: What is the output of the following code. Use single digits for the output of id(x). Program Text: some_list = [1,3,2] def f1(my_list): new_list = [2] print id(my_list), "; ", print id(new_list), ";", print id(some_list), "; ", f1(some_list) Output:
  • 6. Page 6 Program Text: some_list = [1,3,2] def f1(my_list) my_list.append(7) print id(my_list), “;”, return [1,4,5] print id(some_list), “;”, some_list.append(5) print id(some_list), “;”, some_list = [4,3,7] print id(some_list), “;”, some_list = f1(some_list) print id(some_list) Output: Day 6: Mutability Notes: Now that you understand the true nature of a list, we can talk about the concept of mutability. Lists are an example of a mutable object. Mutability is a synonym for changable – in essence, we're saying that you can change a list. Be careful -- while this sounds very simple, it can get quite tricky. For the next problem, the references example will help a lot. Remember that statements like list1 = [1,2,5] change the reference (what the arrow is pointing to) and statements like list1.append(5) change the list itself. Problem 14: What is the output of the following code. Program Text: list1 = [1,2,4] list2 = list1 list2.append(3) print list1 Output:
  • 7. Page 7 Program Text: list1 = [1,2,4] list2 = [1,2,4] list2.append(3) print list1 Output: Program Text: example_list = [1,2,4] def f1(my_list): my_list.append(3) f1(example_list) print example_list Output: Program Text: example_list = [1,2,4] def f1(my_list): my_list = [1,2,4,3] f1(example_list) print example_list Output:
  • 8. Page 8 Program Text: list1 = [1,2,4] list2 = [1,2,4] list3 = list2 list2.append(3) list2 = list1 list2.append(3) list1.append(3) list1 = list3 print list1, ";", print list3 Output: We’ll talk about immutable objects later when we cover tuples and revisit strings. Day 6: Member functions Notes: We saw at the append function earlier – this function had some unusual syntax. Objects have something called member functions. append is a member function of a list. In essence, member functions are basically shorthand. Python could easily have made a general append(some_list, element) function that appends the value of element to the list some_list. Instead, we use the member function of some_list: we write some_list.append(element) to append an element to some_list. In general, member functions have the syntax object_name.function(parameters) – the function affects or applies to the object object_name. Day 4: Lists Redux Notes: Now let's go over lists for real. Remember what you've just learned about them. - Lists are mutable objects. When you change a list somewhere, every other reference will still point to the now changed list. - Lists have member functions. For lists, these functions tend to change the list itself. Basics: You already know how to create a list and read its members. You can also use the example_list[i] syntax to change values, e.g. example_list[1] = 5. Finally, you can write del example_list[i] to delete the element at position i. Length: As mentioned earlier, you can use the built-in function len(x) to find the length of a list.
  • 9. Page 9 Membership: The in operator can be used to determine whether an element is a member of a list or not. 3 in [3,5,7] evaluates to True, while 6 in [3,4,1] evaluates to false. Analogous to !=, you can use not in to check if an element is NOT a member of a list. 12 not in [3,5,7] returns True. Warning: Never use booleans for this operator unless the list consists ONLY of booleans. Recall that the == operator can compare different types; Python considers 0 == False and any other number equal to True. Hence, True in [0,3,5] evaluates to True because 3 == True is considered True by Python. Member functions: All of the following functions change the list they're called from. They have NO return values. - append(element). Appends element to the end of the list. - insert(index, element). Inserts element before the list element at index. - reverse(). Reverses the order of elements in the list. - remove(element). Removes the first instance of element from the list. The following function(s) don’t change the list. They return information about the list instead. - index(element). Returns the position of the first instance of element in the list. - count(element). Returns the number of times element appears in the list. Don’t worry too much about memorizing all these functions. Just keep in mind that they exist. Concatenation: You can combine two lists into a new list with the concatenation operator +. Problem 15: Write a definition for the following shift functions. shift takes a list and moves the first element to the very end. reverse_shift does the opposite – it moves the last element to the beginning of the list. Neither function should return anything! Program Text: def shift(my_list): "Shifts the list [x1,x2,...,xn] to [x2,x3,...,xn,x1]."
  • 10. Page 10 Program Text: def reverse_shift(my_list): "Shifts the list [x1,x2,...,xn] to [xn,x1,x2,...,x(n-1)]." Problem 16: Write a definition for the function last_index. last_index takes a list and an element and returns the position of the last instance of element in list, e.g. last_index([3,4,3,7,9],3) returns 2. Be sure that list is in its original form when your function completes! (either create your own copy of the list or reverse any changes you make.) Program Text: def last_index(my_list, element): "Returns the position of the last instance of element in my_list" Day 4: Advanced Positioning and Slicing Notes: You've already learned about the notation for selecting an element some_list[i] by using its position. You can also use negative numbers to select an element – the last element is considered to have position -1.
  • 11. Page 11 You can do even slicker things. some_list[start:end] creates a list slice – it returns a new list with all the elements between start and end – 1 from the original list. If you omit either start or end, it’ll select all elements from the beginning / up until the end, e.g. some_list[1:] creates a slice including all but the first element. You can change the values of slices the same way you change individual values, e.g. some_list[3:5] = [1,5,4,4,7]. Note that the new assignment doesn’t have to be the same length as the list slice you cut out. Note, however, that if you assign the slice to a variable, that variable points to a new list. Program Text: list1 = [1,3,5,7] list1[1:3] = [2,4,6] print list1 list2 = list1[1:] #list2 points to a new list list2.append(55) print list1 print len(list1) list1[3:5] = [8,8,8,8] print list1 Output: [1, 2, 4, 6, 7] [1, 2, 4, 6, 7] 5 [1, 2, 4, 8, 8, 8, 8] some_list[:] creates a duplicate of the list. This is very useful – since most of our list techniques destructively change the list, many times, it may be a good idea to create a duplicate of the list and mess around with that instead. Problem 17: What is the output of the following code. Program Text: list1 = [4,6,12] list2 = list1[:] list1.append(4) print list2 Output:
  • 12. Page 12 Program Text: list1 = [2,5,6,3] i = 1 while i < len(list1): print list1[-i], ";", i = i + 1 print list1[-len(list1)] Output: Program Text: list1 = [1,2,3] i = 1 while i < len(list1): print list1[:i], ";", i = i + 1 print list1 Output: Day 4: Range function Notes: range(x) is a built-in function that returns a list [0,1,...,x-1], e.g. range(3) returns [0,1,2]. You can also do range(start, finish), which creates the list [start, start+1, ..., finish-1]. Its a very useful function. Day 4: For loop Notes: Like the while loop, the for loop is another control flow command – a way of executing a sequence of statements multiple times. A for loop executes a sequence of statements once for each element in a list. Program Text: for i in [1,2,4,6]: print i, ";", print 8 Output: 1;2;4;6;8
  • 13. Page 13 The for loop is incredibly useful. For example, you can combine the for loop and range(x) function to execute a statement a fixed number of times. Problem 18: Write a definition for a function that takes a list and returns the sum of all elements in that list. Program Text: def sum_elements(my_list): "Returns the sum of all elements in my_list" Day 4: Basic Advanced Loops Notes: This title is not a contradiction :p. For loops can be incredibly difficult to use correctly. This section will give you a bunch of problems to give you practice in solving problems with for loops. Problem 19: Each of the following function definitions takes a list as a parameter and solves a specific problem. Correctly fill the blanks in the following code to solve the problems. There is a way to solve each problem by only filling in the blanks. Don’t just add extra lines to force a solution. Also, there may even be more elegant solutions that don’t use all the blanks – feel free to use those too. Program Text: def all_under_6(my_list): """Returns True if ALL members in my_list are under 6 (False otherwise). my_list must be list of integers.""" under_6 = ___________ for i in my_list: if __________________: _________________________________________________________ return under_6
  • 14. Page 14 Program Text: def no_vowels(my_list): """Returns True if my_list contains only consonants (no vowels). Assume that my_list only contains lowercase letters.""" vowels = ['a','e','i','o','u'] contains_vowels = _________ for i in __________________: if ______________________: ____________________________________________________________ return not contains_vowels Program Text: def find_max_element(my_list): """Finds and returns the maximum value contained in my_list. Assume my_list contains positive values only.""" max_value = -1 for i in __________________: if ______________________: ____________________________________________________________ return max_value