This document provides an introduction to the Python programming language. It discusses Python's basic concepts like data types, control flow, functions, modules and packages. It also covers Python's object-oriented features and how to work with files, exceptions and errors. The tutorial is intended to help readers learn the core elements of the Python language informally through examples and hands-on experience with the Python interpreter.
In a vSphere 5.0 environment, virtual network switches provide connectivity for virtual machines running on VMware® ESXi™ hosts to communicate with each other as well as connectivity to the external physical infrastructure. Network administrators want more visibility into this traffic that is flowing in the virtual infrastructure. This visibility will help them monitor and troubleshoot network issues. VMware vSphere 5.0 introduces two new features in the Distributed Switch that provide the required monitoring and troubleshooting capability to the virtual infrastructure.
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!
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
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.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
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
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.
18. import os
filename = os.environ.get(’PYTHONSTARTUP’)
if filename and os.path.isfile(filename):
execfile(filename)
10 Chapter 2. Using the Python Interpreter ¦^PythonAºì
21. To iterate over the indices of a sequence, combine range() and len() as follows:
s‡ƒ“óv¢Ú'{§Xe¤«@ܦ^range() Úlen() µ
a = [’Mary’, ’had’, ’a’, ’little’, ’lamb’]
for i in range(len(a)):
... print i, a[i]
...
0 Mary
1 had
2 a
3 little
4 lamb
3.4 break and continue Statements, and else Clauses on Loops
Ú
break continue , Šé ±9Ì‚¥
else fé
The break statement, like in C, breaks out of the smallest enclosing for or while loop.
break ŠéÚC ¥'aq§^uaÑg'˜?for ½while Ì‚
The continue statement, also borrowed from C, continues with the next iteration of the loop.
continue Šé´lC ¥G5'§§v«Ì‚U‰‰Ie˜gƒ“
Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with
for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.
This is exemplified by the following loop, which searches for prime numbers:
Ì‚Œ±k˜‡else fé;§QÌ‚ƒ“‡v£éufor ¤½‰I^‡false £éuwhile ¤ž‰
I§¢Ì‚break ¥Ž'œ¹eج‰I±e|¢ƒê'«~§ƒü«
ù‡féµ
for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print n, ’equals’, x, ’*’, n/x
... break
... else:
... # loop fell through without finding a factor
... print n, ’is a prime number’
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
3.4. break and continue Statements, and else Clauses on Loops break Úcontinue Šé, ±9Ì13
‚¥'else fé
23. The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function
when it is called; thus, arguments are passed using call by value (where the value is always an object reference, not
the value of the object).1 When a function calls another function, a new local symbol table is created for that call.
¼êÚ^'¢SëêQ¼êx^žÚÛÜÎÒv§Ïd§¢ëo´DŠx^£ùp'Šo´˜‡é–Ú
^§Ø´Té–'Š¤ ˜‡¼ê,˜‡¼êx^ž§˜‡5'ÛÜÎÒvQx^v§¥Mï
2
A function definition introduces the function name in the current symbol table. The value of the function name has a
type that is recognized by the interpreter as a user-defined function. This value can be assigned to another name which
can then also be used as a function. This serves as a general renaming mechanism:
¼ê½ÂQ¨cÎÒv¥Ú¼ê¶Š^r½Â¼ê§¼ê¶k˜‡Aºì@Œ'aFŠù‡Š
Œ±D‰Ù§·¶§¦ÙUŠ˜‡¼ê5¦^ùÒ”˜‡·¶Å›µ
fib
function fib at 10042ed0
f = fib
f(100)
1 1 2 3 5 8 13 21 34 55 89
You might object that fib is not a function but a procedure. In Python, like in C, procedures are just functions that
don’t return a value. In fact, technically speaking, procedures do return a value, albeit a rather boring one. This value
is called None (it’s a built-in name). Writing the value None is normally suppressed by the interpreter if it would be
the only value written. You can see it if you really want to:
ŒU@fibØ´˜‡¼ê£function ¤§´˜‡v§£procedure ¤Python ÚC ˜$§v§´˜‡
vkˆ£Š'¼ê¢Sþ§lEâþù§v§k˜‡ˆ£Š§,´˜‡Ø?U'ù‡Š¡
None £ù´˜‡S˜·¶¤Xt˜‡Š´None '{§Ï~Aºìج!˜‡None Ñ5§Xtý
Ž‡¦w§'{§Œ±ù$‰µ
print fib(0)
None
It is simple to write a function that returns a list of the numbers of the Fibonacci series, instead of printing it:
±e«~ü«
XÛl¼ê¥ˆ£˜‡¹™Å@êê'êŠóv§Ø´‹§µ
def fib2(n): # return Fibonacci series up to n
... Return a list containing the Fibonacci series up to n.
... result = []
... a, b = 0, 1
... while b n:
... result.append(b) # see below
... a, b = b, a+b
... return result
...
f100 = fib2(100) # call it
f100 # write the result
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
1 Actually, call by object reference would be a better description, since if a mutable object is passed, the caller will see any changes the callee
¯¢þ§¡ƒN^é–Ú^ܷϘ‡ŒCé–D4?5 §N^öŒ±wN^é–?Û?U£XQóL¥¢
makes to it (items inserted into a list).
2
˜‡#f‘¤
3.6. Defining Functions ½Â¼ê 15
24. This example, as usual, demonstrates some new Python features:
Ú±c˜$§ù‡~fü«
˜5'Python õUµ
• The return statement returns with a value from a function. return without an expression argument returns
None. Falling off the end of a procedure also returns None.
return Šél¼ê¥ˆ£˜‡Š§Ø‘vˆª'return ˆ£Nonev§@å ¬ˆ£None
• The statement result.append(b) calls a method of the list object result. A method is a function that
‘belongs’ to an object and is named obj.methodname, where obj is some object (this may be an expression),
and methodname is the name of a method that is defined by the object’s type. Different types define different
methods. Methods of different types may have the same name without causing ambiguity. (It is possible to define
your own object types and methods, using classes, as discussed later in this tutorial.) The method append()
shown in the example is defined for list objects; it adds a new element at the end of the list. In this example it is
equivalent to ‘result = result + [b]’, but more efficient.
Šéresult.append(b) ¡óvé–result '˜‡{£method ¤{´˜‡/áu0
,‡é–'¼ê§§·¶obj.methodename §ùp'obj ´,‡é–£ŒU´˜‡vˆ
ª¤§methodename ´,‡QTé–aF½Â¥'{'·¶ØÓ'aF½ÂØÓ'{
ØÓaFŒUkÓ$¶i'{§¢Ø¬· £¨½ÂgC'é–aFÚ{ž§ŒU¬Ñyù
«œ¹§)H ¡'Ù3¬HXÛ¦^a.¤«~¥ü«'append(){dóv閽§
§•óv¥˜‡5£ƒQ«~¥§1Óu‘result = result + [b]’§Øv¨Çp
3.7 More on Defining Functions ¼ê½Â
It is also possible to define functions with a variable number of arguments. There are three forms, which can be
combined.
kžs‡½Âëê‡êŒg'¼êkn‡{Œ±ˆ 8'§·‚Œ±|ܦ^§‚
3.7.1 Default Argument Values ëê%@Š
The most useful form is to specify a default value for one or more arguments. This creates a function that can be called
with fewer arguments than it is defined to allow. For example:
k^'Gª´‰˜‡½õ‡ëê½%@Šù$Mï'¼êŒ±^¨'ëê5x^~Xµ
def ask_ok(prompt, retries=4, complaint=’Yes or no, please!’):
while True:
ok = raw_input(prompt)
if ok in (’y’, ’ye’, ’yes’): return True
if ok in (’n’, ’no’, ’nop’, ’nope’): return False
retries = retries - 1
if retries 0: raise IOError, ’refusenik user’
print complaint
This function can be called either like this: ask_ok(’Do you really want to quit?’) or like this:
ask_ok(’OK to overwrite the file?’, 2).
ù‡¼ê„Œ±^±e'ªx^µask_ok(’Do you §½ö”ù
$µask_ok(’OK to overwrite the file?’, 2)
really want to quit?’)
This example also introduces the in keyword. This tests whether or not a sequence contains a certain value.
ù‡«~„H
9…iin §uÿ˜‡ƒ¥´Ä¹,‡‰½'Š
16 Chapter 3. More Control Flow Tools )6§››
25. The default values are evaluated at the point of function definition in the defining scope, so that
%@ŠQ¼ê½ÂãAÛ§Xe¤«µ
i = 5
def f(arg=i):
print arg
i = 6
f()
will print 5.
±þ“謋5
Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable
object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the
arguments passed to it on subsequent calls:
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
This will print
ù¬‹Ñµ
[1]
[1, 2]
[1, 2, 3]
If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:
XtØŽQØÓ'¼êx^ƒm¡ëê%@Š§Œ±Xe¡'¢~˜$c!¼êµ
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
3.7.2 Keyword Arguments
Functions can also be called using keyword arguments of the form ‘keyword = value’. For instance, the following
function:
¼êŒ±Ïv9…iëê'Gª5x^§GX‘keyword = value’ ~X§±e'¼êµ
3.7. More on Defining Functions )¼ê½Â 17
26. def parrot(voltage, state=’a stiff’, action=’voom’, type=’Norwegian Blue’):
print -- This parrot wouldn’t, action,
print if you put, voltage, volts through it.
print -- Lovely plumage, the, type
print -- It’s, state, !
could be called in any of the following ways:
Œ±^±e'?˜{x^µ
parrot(1000)
parrot(action = ’VOOOOOM’, voltage = 1000000)
parrot(’a thousand’, state = ’pushing up the daisies’)
parrot(’a million’, ’bereft of life’, ’jump’)
but the following calls would all be invalid:
Øv±eA«x^´Ã¨'µ
parrot() # required argument missing
parrot(voltage=5.0, ’dead’) # non-keyword argument following keyword
parrot(110, voltage=220) # duplicate value for argument
parrot(actor=’John Cleese’) # unknown keyword
In general, an argument list must have any positional arguments followed by any keyword arguments, where the
keywords must be chosen from the formal parameter names. It’s not important whether a formal parameter has a
default value or not. No argument may receive a value more than once — formal parameter names corresponding to
positional arguments cannot be used as keywords in the same calls. Here’s an example that fails due to this restriction:
Ï~§ëêv¥'z˜‡9…iÑUv5guGªëê§z‡ëêÑkéA'9…iGªëêkvk
%@Š¿Ø‡¢SëêØU˜gDõ‡Š))GªëêØUQÓ˜gx^¥Óž¦^ ˜Ú9…i”
½Šùpk˜‡~fü«
Qù«!åe¤Ñy'”}œ¹µ
def function(a):
... pass
...
function(0, a=0)
Traceback (most recent call last):
File stdin, line 1, in ?
TypeError: function() got multiple values for keyword argument ’a’
When a final formal parameter of the form **name is present, it receives a dictionary containing all keyword argu-
ments except for those corresponding to a formal parameter. This may be combined with a formal parameter of the
form *name (described in the next subsection) which receives a tuple containing the positional arguments beyond the
formal parameter list. (*name must occur before **name.) For example, if we define a function like this:
Ú˜‡GX**name 'ëꞧ§Â˜‡iY §TiY¹
¤k™ÑyQGªëêv¥'9…i
ëêùpŒU„¬|ܦ^˜‡GX*name 'Gªëꧧ˜‡£|£e˜3¥¬[H¤§
¹
¤kvkÑyQGªëêv¥'ëꊣ*name UvQ**name ƒcÑy¤~X§·‚ù$½Â˜
‡¼êµ
18 Chapter 3. More Control Flow Tools )6§››
27. def cheeseshop(kind, *arguments, **keywords):
print -- Do you have any, kind, ’?’
print -- I’m sorry, we’re all out of, kind
for arg in arguments: print arg
print ’-’*40
keys = keywords.keys()
keys.sort()
for kw in keys: print kw, ’:’, keywords[kw]
It could be called like this:
§Œ±”ù$x^µ
cheeseshop(’Limburger’, It’s very runny, sir.,
It’s really very, VERY runny, sir.,
client=’John Cleese’,
shopkeeper=’Michael Palin’,
sketch=’Cheese Shop Sketch’)
and of course it would print:
¨,§¬UXeSN‹µ
-- Do you have any Limburger ?
-- I’m sorry, we’re all out of Limburger
It’s very runny, sir.
It’s really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
Note that the sort() method of the list of keyword argument names is called before printing the contents of the
keywords dictionary; if this is not done, the order in which the arguments are printed is undefined.
5¿sort(){Q9…iiYSN‹cx^§Äu'{§‹ëêž'^ƒ´™½Â'
3.7.3 Arbitrary Argument Lists ŒCëêL
Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of argu-
ments. These arguments will be wrapped up in a tuple. Before the variable number of arguments, zero or more normal
arguments may occur.
§˜‡Ø~^'Àt´Œ±4¼êx^Œg‡ê'ëêùëêCc˜‡£|QùŒg
‡ê'ëêƒc§Œ±k õ‡ÊÏ'ëêµ
def fprintf(file, format, *args):
file.write(format % args)
3.7. More on Defining Functions )¼ê½Â 19
30. def my_function():
... Do nothing, but document it.
...
... No, really, it doesn’t do anything.
...
... pass
...
print my_function.__doc__
Do nothing, but document it.
No, really, it doesn’t do anything.
22 Chapter 3. More Control Flow Tools )6§››
31. CHAPTER
FOUR
Data Structures êâ(¨
This chapter describes some things you’ve learned about already in more detail, and adds some new things as well.
)Ù3)ù㘮²ÆSv'Àܧ¿…„
5'SN
4.1 More on Lists óL
The list data type has some more methods. Here are all of the methods of list objects:
óvaFkéõ{§ùp´óvaF'¤k{µ
append(x)
Add an item to the end of the list; equivalent to a[len(a):] = [x].
r˜‡£ƒV óv'@—§ƒ¨ua[len(a):] = [x]
extend(L)
Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.
ÏvV½óv'¤k£ƒ5*¿óv§ƒ¨ua[len(a):] = L
insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to in-
sert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to
a.append(x).
Q½ ˜¢˜‡£ƒI˜‡ëê´O#¢ Ùc¡'@‡£ƒ'¢Ú§~
Xa.insert(0,x) ¬¢ ‡óvƒc§a.insert(len(a), x) ƒ¨ua.append(x)
remove(x)
Remove the first item from the list whose value is x. It is an error if there is no such item.
íØóv¥Šx'I˜‡£ƒXtvkù$'£ƒ§Ò¬ˆ£˜‡†Ø
pop([i ])
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes
and returns the last item in the list. (The square brackets around the i in the method signature denote that
the parameter is optional, not that you should type square brackets at that position. You will see this notation
frequently in the Python Library Reference.)
lóv'½ ˜íØ£ƒ§¿òÙˆ£Xtvk½¢Ú§a.pop() ˆ£ ˜‡£ƒ£ƒ
‘=lóv¥íØ£{¥i üb')Òv«ù‡ëê´ŒÀ'§Ø´‡¦Ñ˜é)
Ò§¬²~QPython ¥ëÃþ¥‘ ù$'sP¤
index(x)
Return the index in the list of the first item whose value is x. It is an error if there is no such item.
ˆ£óv¥I˜‡Šx '£ƒ'¢ÚXtvkš''£ƒÒ¬ˆ£˜‡†Ø
23
35. def sum(seq):
... def add(x,y): return x+y
... return reduce(add, seq, 0)
...
sum(range(1, 11))
55
sum([])
0
؇”«~¥ù$½Â µÏÜOêŠ
Don’t use this example’s definition of sum(): since summing numbers is such a common need, a built-in function
´˜‡Ï^'s¦§Q ‡¥§Jø
S˜' ¼ê
sum(sequence) is already provided, and works exactly like this. sum()
2.3 sum(sequence) New in version 2.3.
4.1.4 List Comprehensions óLíª
List comprehensions provide a concise way to create lists without resorting to use of map(), filter() and/or
lambda. The resulting list definition tends often to be clearer than lists built using those constructs. Each list
comprehension consists of an expression followed by a for clause, then zero or more for or if clauses. The result
will be a list resulting from evaluating the expression in the context of the for and if clauses which follow it. If the
expression would evaluate to a tuple, it must be parenthesized.
óvíªJø
˜‡Mïóv'{ü廧Ãs¦^map()§filter() ±9lambdaˆ£óv'½Â
Ï~‡9Mïùóv˜ßz˜‡óvíª)Q˜‡for Šéƒ 'vˆª§½õ‡for½if
Šéˆ£Š´dfor ½ifféƒ 'vˆª '£ƒ|¤'óvXtŽ‡ ˜‡£|§Uv‡
þ)Ò
freshfruit = [’ banana’, ’ loganberry ’, ’passion fruit ’]
[weapon.strip() for weapon in freshfruit]
[’banana’, ’loganberry’, ’passion fruit’]
vec = [2, 4, 6]
[3*x for x in vec]
[6, 12, 18]
[3*x for x in vec if x 3]
[12, 18]
[3*x for x in vec if x 2]
[]
[[x,x**2] for x in vec]
[[2, 4], [4, 16], [6, 36]]
[x, x**2 for x in vec] # error - parens required for tuples
File stdin, line 1, in ?
[x, x**2 for x in vec]
^
SyntaxError: invalid syntax
[(x, x**2) for x in vec]
[(2, 4), (4, 16), (6, 36)]
vec1 = [2, 4, 6]
vec2 = [4, 3, -9]
[x*y for x in vec1 for y in vec2]
[8, 6, -18, 16, 12, -36, 24, 18, -54]
[x+y for x in vec1 for y in vec2]
[6, 5, -7, 8, 7, -5, 10, 9, -3]
[vec1[i]*vec2[i] for i in range(len(vec1))]
[8, 12, -54]
4.1. More on Lists )óv 27
38. combination of tuple packing and sequence unpacking!
ù‡x^¡S
µš~Ü·ƒµ‡¦†ý'gþê8†ƒ'£ƒ‡êƒÓ‡5¿'´Œ
gëê£multiple assignment ¤Ù¢´£|µCÚƒµ'˜‡@Üœ
There is a small bit of asymmetry here: packing multiple values always creates a tuple, and unpacking works for any
sequence.
ùpk˜XØ页µCõëêÏ~¬M£|§µöŠŒ±Š^u?Ûƒ
4.4 Sets 8Ü
Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses
include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like
union, intersection, difference, and symmetric difference.
„¹
˜‡êâaF))set£8ܤ8Ü´˜‡ÃƒØE£ƒ'8Ä)õU)9X
ÿÁÚžØE£ƒ8Üé–„|±union£éܤ§intersection£¢¤§difference£¤Úsysmmetric
Python
difference£é¡8¤1êÆ6Ž
Here is a brief demonstration:
±e´˜‡{ü'ü«µ
basket = [’apple’, ’orange’, ’apple’, ’pear’, ’orange’, ’banana’]
fruit = set(basket) # create a set without duplicates
fruit
set([’orange’, ’pear’, ’apple’, ’banana’])
’orange’ in fruit # fast membership testing
True
’crabgrass’ in fruit
False
# Demonstrate set operations on unique letters from two words
...
a = set(’abracadabra’)
b = set(’alacazam’)
a # unique letters in a
set([’a’, ’r’, ’b’, ’c’, ’d’])
a - b # letters in a but not in b
set([’r’, ’d’, ’b’])
a | b # letters in either a or b
set([’a’, ’c’, ’r’, ’d’, ’b’, ’m’, ’z’, ’l’])
a b # letters in both a and b
set([’a’, ’c’])
a ^ b # letters in a or b but not both
set([’r’, ’d’, ’b’, ’m’, ’z’, ’l’])
4.5 Dictionaries i;
Another useful data type built into Python is the dictionary. Dictionaries are sometimes found in other languages
as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers,
dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples
can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either
30 Chapter 4. Data Structures êâ@¨
40. dict([(’sape’, 4139), (’guido’, 4127), (’jack’, 4098)])
{’sape’: 4139, ’jack’: 4098, ’guido’: 4127}
dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension
{2: 4, 4: 16, 6: 36}
Later in the tutorial, we will learn about Generator Expressions which are even better suited for the task of supplying
key-values pairs to the dict() constructor.
Q€H ¡'SN¥§·‚ò¬ÆS·udict() ¨iìA¤…Šé'A¤ìvˆª
When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:
¦^{üiÎGŠ9…i'{§Ï~^9…iëê{ü
dict(sape=4139, guido=4127, jack=4098)
{’sape’: 4139, ’jack’: 4098, ’guido’: 4127}
4.6 Looping Techniques Ì‚Eâ
When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the
iteritems() method.
QiY¥Ì‚ž§9…iÚéA'ŠŒ±¦^iteritems(){ÓžAÖÑ5
knights = {’gallahad’: ’the pure’, ’robin’: ’the brave’}
for k, v in knights.iteritems():
... print k, v
...
gallahad the pure
robin the brave
When looping through a sequence, the position index and corresponding value can be retrieved at the same time using
the enumerate() function.
Qƒ¥Ì‚ž§¢Ú ˜ÚéAŠŒ±¦^enumerate()¼êÓž
for i, v in enumerate([’tic’, ’tac’, ’toe’]):
... print i, v
...
0 tic
1 tac
2 toe
To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
Ӟ̂ü‡½õ'ƒ§Œ±¦^zip() NAÖ
32 Chapter 4. Data Structures êâ@¨