Python is a widely used high-level programming language for general-purpose programming. Python is a simple, powerful and easy to learn the programming language. It is commonly used for Web and Internet development, Scientific and Numeric computing, Business application and Desktop GUI development etc. The basic data structures in python are lists, dictionaries, tuples, strings and sets
METHODS DESCRIPTION
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the given key.
popitem() Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
get() It is a conventional method to access a value for a key.
dictionary_name.values() returns a list of all the values available in a given dictionary.
str() Produces a printable string representation of a dictionary.
update() Adds dictionary dict2’s key-values pairs to dict
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict’s keys
items() Returns a list of dict’s (key, value) tuple pairs
has_key() Returns true if key in dictionary dict, false otherwise
fromkeys() Create a new dictionary with keys from seq and values set to value.
type() Returns the type of the passed variable.
cmp() Compares elements of both dict.
Python is a widely used high-level programming language for general-purpose programming. Python is a simple, powerful and easy to learn the programming language. It is commonly used for Web and Internet development, Scientific and Numeric computing, Business application and Desktop GUI development etc. The basic data structures in python are lists, dictionaries, tuples, strings and sets
METHODS DESCRIPTION
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the given key.
popitem() Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
get() It is a conventional method to access a value for a key.
dictionary_name.values() returns a list of all the values available in a given dictionary.
str() Produces a printable string representation of a dictionary.
update() Adds dictionary dict2’s key-values pairs to dict
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict’s keys
items() Returns a list of dict’s (key, value) tuple pairs
has_key() Returns true if key in dictionary dict, false otherwise
fromkeys() Create a new dictionary with keys from seq and values set to value.
type() Returns the type of the passed variable.
cmp() Compares elements of both dict.
Python is powerful... and fast; plays well with others; runseverywhere; is friendly & easy to learn;
is Open.These are some of the reasons people who use Python would rather not use anything else.
This presentation is all about various built in
datastructures which we have in python.
List
Dictionary
Tuple
Set
and various methods present in each data structure
All data values in Python are encapsulated in relevant object classes. Everything in Python is an object and every object has an identity, a type, and a value. Like another object-oriented language such as Java or C++, there are several data types which are built into Python. Extension modules which are written in C, Java, or other languages can define additional types.
To determine a variable's type in Python you can use the type() function. The value of some objects can be changed. Objects whose value can be changed are called mutable and objects whose value is unchangeable (once they are created) are called immutable.
The Key Difference between a List and a Tuple. The main difference between lists and a tuples is the fact that lists are mutable whereas tuples are immutable. A mutable data type means that a python object of this type can be modified. Let's create a list and assign it to a variable.
Introduction to the basics of Python programming (part 3)Pedro Rodrigues
This is the 3rd part of a multi-part series that teaches the basics of Python programming. It covers list and dict comprehensions, functions, modules and packages.
Ubiquitous computing will require design that reflects the strengths and weaknesses of humanity, says Professor Alan Hedge, Director of the Human Factors and Ergonomics Laboratory at Cornell University.
Python is powerful... and fast; plays well with others; runseverywhere; is friendly & easy to learn;
is Open.These are some of the reasons people who use Python would rather not use anything else.
This presentation is all about various built in
datastructures which we have in python.
List
Dictionary
Tuple
Set
and various methods present in each data structure
All data values in Python are encapsulated in relevant object classes. Everything in Python is an object and every object has an identity, a type, and a value. Like another object-oriented language such as Java or C++, there are several data types which are built into Python. Extension modules which are written in C, Java, or other languages can define additional types.
To determine a variable's type in Python you can use the type() function. The value of some objects can be changed. Objects whose value can be changed are called mutable and objects whose value is unchangeable (once they are created) are called immutable.
The Key Difference between a List and a Tuple. The main difference between lists and a tuples is the fact that lists are mutable whereas tuples are immutable. A mutable data type means that a python object of this type can be modified. Let's create a list and assign it to a variable.
Introduction to the basics of Python programming (part 3)Pedro Rodrigues
This is the 3rd part of a multi-part series that teaches the basics of Python programming. It covers list and dict comprehensions, functions, modules and packages.
Ubiquitous computing will require design that reflects the strengths and weaknesses of humanity, says Professor Alan Hedge, Director of the Human Factors and Ergonomics Laboratory at Cornell University.
Although people may be very accustomed to reading and understanding .docxmilissaccm
Although people may be very accustomed to reading and understanding calculations like those in the preceding assignments, it is evident they are not very self-evident or obvious in the world of computing. One way to simplify the problem is just to redefine how expressions are represented, to allow for simpler interpretation.
One knows that a plus sign means to add, but typically when a plus sign is encountered in the middle of an expression, there is not yet enough information to know what values are to be added. One has to continue scanning the expression to find the second operand, and also decide if there are other operations of higher precedence that must take place first. How much simpler it would be if a parser could know to add just as soon as the plus sign appears.
This is the motivation for a representation called
postfix
notation, in which all operators
follow
their operands. Here are some illustrations.
Infix Representation
Postfix Representation
Operations
(1 + 2) * 3
1 2 + 3 *
Add 1 and 2, then multiply by 3
1 + (2 * 3)
1 2 3 * +
Multiply 2 and 3, then add to 1
(1+2) * (6-4)
1 2 + 6 4 - *
Add 1 and 2, subtract 4 from 6, multiply
Hewlett Packard has produced a line of calculators that expected all inputs to be in postfix form, so every operation key could compute the moment it was pressed.
The goal of this assignment is to convert an infix expression into a postfix expression. This can be accomplished using the same algorithm as was used to evaluate the infix expression, simply yielding a new expression instead of a computed value. In the last example, instead of adding, it would produce an expression ending with a plus sign. The multiplication function would similarly produce an expression from its operands, followed by the multiplication operator.
Applying a Linked List
One of the purposes of this course is to find the data structures that would assist in producing the best results as efficiently as possible. The linked list is quite serviceable for the needs of this assignment.
A linked list will be useful in the calculation portion of this assignment. As the postfix expression is scanned, values must be saved until an operator is discovered. Each operator would apply to the two values that precede it, and then its result would also be saved. As an extreme example, consider this expression:
1 2 3 4 5 * - + - multiply 4 * 5, subtract from 3, add to 2, subtract from 1
Note this is not at all the same meaning as:
1 2 * 3 - 4 + 5 - or 4 5 * 3 - 2 + 1 -
(If you need to more clearly see the difference, try inserting parentheses around all operations, such that each parentheses consists of two expressions followed by an operator.)
Defining a Linked List
The linked list is a rather simple data structure, and the required operations should be rather simple, so very little will be said here about what to do. Instead, here is a quick highlight of what should appear in your implementation..
Assg 07 Templates and Operator OverloadingCOSC 2336 Sprin.docxfestockton
Assg 07: Templates and Operator Overloading
COSC 2336 Spring 2019
Dates:
Due: Thursday March 07, by Midnight (note the di�erent due date)
Objectives
� Practice creating a more realistic abstract data type ADT
� Using operator overloading to do output, insertion and access into a
list.
� Use templates so our ADT can hold objects of any type
Description
In this assignment you will be practicing operator overloading. I will also,
for extra credit, give an additional task to convert your class into a class
template, so that it will work as a container for any type.
In this assignment you will be expanding on / creating a new version of
the ListType data type we have seen examples of before in class. Your task is
to create a ListType that holds a list of integers. You will be asked to create
several member functions, and then to create several overloaded operators
for your list of integers. Your basic task is to user operator overloading to
support appending and prepending to a list, outputting the list as a string
and to an output stream, accessing the list (using the indexing operator[]),
and concatenating lists together (using operator+).
I have given you a starting template for your ListType that already
contains 3 versions of the class constructor. I have also already provided you
the operator= implementation, to provide the copy operator for your class.
You should �rst get your class to work as a simple ListType that holds a
list of integers. If you get your class working for integers and submit it, you
1
can then turn your class into a template class, so that your list can work on
objects of any type. I will give up to 10 bonus points for implementations of
working class templates, if you �rst mostly have your basic ListType working
for simple integers. As usual I have also given a �le with a main function
and a lot of commented out tests. You should implement the class member
functions in the order speci�ed next, commenting out each test one at a time,
to incrementally develop and test your ListType class implementation.
For this assignment you need to perform the following tasks.
1. As mentioned in the starting template I have given you a starting class
de�nition, some class constructors and the destructor, and the copy
operator=. You �rst need to write two simple getter methods in order
to access the size and allocSize class member values. These should be
called getSize() and getAllocSize() respectively. These functions
should be class const functions (you guarantee that calling them will
not cause the class to be modi�ed. These functions take no parameters
as input. They both return an int value, because the size and allocSize
member parameters are both integer values.
2. Write a function called tostring(). This function will be a const class
function (the class is not modi�ed when it is called). This function
takes no parameters as input, and it returns a string. We use this
function in our testing, so you need to get ...
A for loop is probably the most common type of loop in Python. A for loop will select items from any iterable. In Python an iterable is any container (list, tuple, set, dictionary), as well as many other important objects such as generator function, generator expressions, the results of builtin functions such as filter, map, range and many other items.
This presentation covers a detailed overview of python advanced concepts. it covers the below aspects.
Comprehensions
Lambda with (map, filter and reduce)
Context managers
Iterator, Generators, Decorators
Python GIL and multiprocessing and multithreading
Python WSGI
Python Unittests
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Transcript: Selling digital books in 2024: Insights from industry leaders - T...BookNet Canada
The publishing industry has been selling digital audiobooks and ebooks for over a decade and has found its groove. What’s changed? What has stayed the same? Where do we go from here? Join a group of leading sales peers from across the industry for a conversation about the lessons learned since the popularization of digital books, best practices, digital book supply chain management, and more.
Link to video recording: https://bnctechforum.ca/sessions/selling-digital-books-in-2024-insights-from-industry-leaders/
Presented by BookNet Canada on May 28, 2024, with support from the Department of Canadian Heritage.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Welocme to ViralQR, your best QR code generator.ViralQR
Welcome to ViralQR, your best QR code generator available on the market!
At ViralQR, we design static and dynamic QR codes. Our mission is to make business operations easier and customer engagement more powerful through the use of QR technology. Be it a small-scale business or a huge enterprise, our easy-to-use platform provides multiple choices that can be tailored according to your company's branding and marketing strategies.
Our Vision
We are here to make the process of creating QR codes easy and smooth, thus enhancing customer interaction and making business more fluid. We very strongly believe in the ability of QR codes to change the world for businesses in their interaction with customers and are set on making that technology accessible and usable far and wide.
Our Achievements
Ever since its inception, we have successfully served many clients by offering QR codes in their marketing, service delivery, and collection of feedback across various industries. Our platform has been recognized for its ease of use and amazing features, which helped a business to make QR codes.
Our Services
At ViralQR, here is a comprehensive suite of services that caters to your very needs:
Static QR Codes: Create free static QR codes. These QR codes are able to store significant information such as URLs, vCards, plain text, emails and SMS, Wi-Fi credentials, and Bitcoin addresses.
Dynamic QR codes: These also have all the advanced features but are subscription-based. They can directly link to PDF files, images, micro-landing pages, social accounts, review forms, business pages, and applications. In addition, they can be branded with CTAs, frames, patterns, colors, and logos to enhance your branding.
Pricing and Packages
Additionally, there is a 14-day free offer to ViralQR, which is an exceptional opportunity for new users to take a feel of this platform. One can easily subscribe from there and experience the full dynamic of using QR codes. The subscription plans are not only meant for business; they are priced very flexibly so that literally every business could afford to benefit from our service.
Why choose us?
ViralQR will provide services for marketing, advertising, catering, retail, and the like. The QR codes can be posted on fliers, packaging, merchandise, and banners, as well as to substitute for cash and cards in a restaurant or coffee shop. With QR codes integrated into your business, improve customer engagement and streamline operations.
Comprehensive Analytics
Subscribers of ViralQR receive detailed analytics and tracking tools in light of having a view of the core values of QR code performance. Our analytics dashboard shows aggregate views and unique views, as well as detailed information about each impression, including time, device, browser, and estimated location by city and country.
So, thank you for choosing ViralQR; we have an offer of nothing but the best in terms of QR code services to meet business diversity!
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfPeter Spielvogel
Building better applications for business users with SAP Fiori.
• What is SAP Fiori and why it matters to you
• How a better user experience drives measurable business benefits
• How to get started with SAP Fiori today
• How SAP Fiori elements accelerates application development
• How SAP Build Code includes SAP Fiori tools and other generative artificial intelligence capabilities
• How SAP Fiori paves the way for using AI in SAP apps
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
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:
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