Python for dummies pdf 2019 free download






















Some used copies are also available on sale at the lowest prices. Machine Learning For Dummies is one of the best books that learns this latest technology in a simple but systematic manner. This pdf book will help you to learn machine learning or deep learning from scratch in simple yet systematic manner. I know many of readers who did well after reading this book. No, this book is specifically written for the beginner's with little to zero prior knowledge.

This book is divided into 6 parts and every part is further divided into different chapters discussing every aspect of machine learning in detail. Save my name, email, and website in this browser for the next time I comment. Terms and Conditions. Press ESC to close. Table of Contents. Buy Paperback Edition Of Book:. Additional Information About Book:. Frequently Asked Questions. Is any Prior Experience required to learn from this book? How many chapters are in this machine learning pdf?

PDF eBooks. Show Comments. Leave a Reply Cancel reply. If the link passes the tests, it's added to the self. URLs set and the self. Designing for expansion To understand another design decision in the spider. It checks whether the link is part of the Web site. We decided to make a separate method for another reason: doing so makes it easier to subclass Spider. Subclassing is making a new class that shares most of the features of a class but either overrides or extends some of its functionality.

Chapter 13 has more about subclassing. The current program handles only one type at a time. This illustrates another good programming practice. But don't overdesign or add features before they're needed.

Python programs are easy to change, so you can quickly add features when necessary. This is an example of the design philosophy described in the preceding paragraph. Function and method tidbits The spider.

This is called a default parameter. It means that when you make an instance of the Spider class, you can specify a parameter for log, but you don't have to. If you don't, the instance automatically uses None as the value for log. Default parameters give you choices and make your code more flexible. Because of the default log parameter, a number of different options for logging can be used with the Spider class. Chapters 3, 11, and 13 describe how to use functions, methods, and classes.

Looping around The spider. Chapter 10 shows you more ways to use loops. Collections of data Sets, lists, and dicts are Python's data types for dealing with collections of data, especially if the data change while the program is running. Lists Lists described more fully in Chapter 8 are most efficient, which is one reason we used a list self.

Sets Sets are a good way of handling data when you want to ignore or avoid duplicates. Chapter 9 shows more ways to use sets. Tip If we had wanted to associate some data with each URL in the Web page, we would have used a dict. Chapter 9 shows you how. Naming names If a good name is one that helps you understand what the named object is doing, then there are some good names and some not-so-good names in spider. Tip Programmers sometimes choose terse and not very explanatory names on purpose to indicate that you shouldn't pay much attention to the name because it's just a temporary name used to convey information for example, it's used as an argument to a function or method.

Sometimes a temporary name makes a few lines of code easier to read. HTMLParser formatter. AbstractFormatter writer But that's kind of long and hard to read, so we decided it was better to split the lines and use a temporary name.

REMEMBER Give users of your modules information about which attributes, functions, classes, and methods they should avoid accessing directly, passing to other functions, subclassing, or rewriting. See Chapter 13 for more about private attributes. For example, we chose to make self. Unsurprisingly, startswith checks whether a string starts with a particular substring.

The urljoin function as the name suggests—see the benefits of naming things well? The Cheat Sheet lists the most commonly used string methods. Handling errors One error-handling tool in the spider.

Its purpose is to catch errors from the urllib2. What spider. For example, if you try to run the program from the command line without specifying a URL, the program fails messily. Because lots of programmers talk about the benefits of comments, documentation, and error-checking, but lots of programs some written by those same programmers don't do as good of a job on those things as they should.

This is a "Do as we say, not as we do" situation. Similarly, garbage in the HTML can cause the htmllib module's parser to choke, so the line parser.

This chapter focuses on what they do the rest of the time. Sometimes, there's no difference between meetings and wasted time. The Three Ds If you're writing a program that's more than a few lines long, don't just sit down and start coding. You need to take three steps to make your program the best it can be.

That means your code is part of the documentation, too. For example, picking good names is part of documentation! Before you even start writing your program, it's a good idea to write notes about the goal of the program. Pretend you need to explain it to someone else—and if you have someone to read the notes, so much the better. Warning If you don't write documentation, you will find it difficult to use or maintain your program after letting it sit for six months even if you're the only person who uses the program.

Designing Designing is actually shorthand for two intertwined parts of programming: analysis and design. What do you really want? Analysis is the process of determining what problem you're trying to solve. It's similar to the process an architect makes you go through to remodel your kitchen: "What do you really want? After you have some specific ideas of what you want, the design phase starts. The blueprint isn't the kitchen itself; it's the plan that needs to be followed to build the new kitchen.

If you're writing a program, you start to build the outline of the program, which is similar to a blueprint. In fact, people who focus on the analysis and design of programs are often called software architects.

You write a sketch of what your program will do, using the structures you'll need to use when you write the program such as class and function definitions and if statements , but you don't bother with the syntax details necessary to write working code.

When the pseudo-coding process is finished, the details are easy to fill in. Some people will tell you, though, that the term derives from an incident in which an actual insect was found to be causing glitches inside an early computer in Although bug is older than writing programs, debugging has been an inherent part of writing software since people started writing software.

One of the first computer scientists, Maurice Wilkes, is reputed to have said, "I can remember the exact instant when I realized that a large part of my life from then on was going to be spent in finding mistakes in my own programs. The architect's constraints include time, money, good taste, and the structural limits of the materials.

Programming also requires balancing multiple needs—often including time, money, the feature requests of multiple groups of people, and the availability of sufficient quantities of caffeine.

We consider them the best distillation of the Python philosophy of programming. They're meant to encourage you to think. In some cases the principles may appear contradictory. That's a reflection of the fact that programming sometimes requires balancing conflicting requirements. It's like the old saying: "Good, fast, cheap—pick any two. The principles were originally written to guide the development of Python itself, but they also apply to writing your own programs. That's how we discuss them here.

Some of the most important guidelines are these: Explicit is better than implicit. For example, printing to the screen shouldn't erase your hard drive. Readability counts. A good program is easy for a human to read and understand. If two blocks of code produce the same result, consider using the one that's easier to read.

Sometimes cryptic code runs faster, but speed isn't the primary goal of most Python programming. Errors should never pass silently. There should be one—and preferably only one—obvious way to do it. This guideline "There's only one way," for short is the most popular among people in the Python community.

Using standard idioms saves time because the code is already mostly written; you just plug in your data and variables. Python For Dummies includes many standard idioms to get you started. Typing import this at the Python prompt in Python 2. Explicit is better than implicit. Simple is better than complex.

Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Special cases aren't special enough to break the rules. Although practicality beats purity. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it.

Although that way may not be obvious at first unless you're Dutch Now is better than never. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea.

Namespaces are one honking great idea -- let's do more of those! Most computer programs have bugs. As you get comfortable with programming and Python, you get a better sense for how the computer "thinks," which helps you figure out bugs more quickly.

Missing punctuation is the most common syntax mistake. Not the Knights who say 'Ni'! If you name an object and then misspell the name when you refer to it later, you'll get an error. The best way to find out about common bugs other than writing your own programs is to look at the bugs other people make. The comp. See Chapter 22 to find out how to access these resources.

The same errors come up over and over, and you'll soon be able to recognize them on sight. Tip For helpful debugging tips, see "Debugging Strategies," later in this chapter. Now what? Chances are you'll want to make some changes soon. In fact, most programmers spend far more time changing existing programs than writing new ones.

When you want to update your code, you'll likely be tempted to change it in a way that doesn't take a lot of time. But that might not be the best way to go about it in the long run.

Suppose you've written a program to send yourself a daily e-mail with the top ten lines from your calendar file. It might look like Listing SMTP 'mail' replace 'mail' with the name of your mailhost smtp. The simple, easy —and wrong—way to do it, illustrated in Listing , is called cut-'n'-paste programming. Note how most of the lines of the program are repeated in the if and else statements.

By the way, another change made in the program was the addition of sys. That's not bad programming, we just wanted to point it out. Listing calendar. SMTP 'mail' smtp. This is called refactoring the code.

Refactoring a program works like this: 1. Figure out the elements that are common to all the tasks the program performs. In this example, the common element is that both tasks sending a daily calendar and sending a weekly calendar involve sending an e-mail. Put the common elements into one or more functions. Many of those methods are combined under the umbrella of Extreme Programming XP. Some programmers have always wanted to be as cool as skateboarders. Maybe using a term like this helps.

Or maybe not. For example, one of the best ways of getting bugs out of a program is to have another programmer review the code.

Well, why not have the second programmer review the code while you're writing it? Similarly, if writing unit tests is good, maybe you should write the tests before you start writing code. That's called test-driven development. Wikipedia to the rescue! Although refactoring will take you longer the first time you change your program, it will save you time in the long run, and it will also make your program more generally useful and easier to read.

The refactored version of the calendar. But if you extended the program via the cut-'n'-paste method, your program would get longer very quickly, and if you made changes to the code that reads the calendar file and sends the e-mail, you'd have to make those changes multiple times.

A general rule to use: Refactor if at least three lines of code are duplicated in your program. The refactored program looks like Listing They'll help with documenting, debugging, and maintaining the program later. Tip The conventions are available on the python. Some computers don't handle long filenames or names with special characters. This practice makes it easier for users of other operating systems to use your program.

This helps anyone reading or debugging your program to recognize exceptions right away. Avoid tabs. He has ceased to be! Include comments as you write the program. Comments should describe why the code is written the way it is and not just what it does. Chunks of code, such as functions, are usually preceded by comments that describe the whole chunk not comments that go with each line.

This block includes the type of file, the name of the programmer, the date of creation, the purpose of the file, and usage instructions. See the following section, "Built-in functions," to find out about these three useful functions. See "Using a debugger" later in this chapter.

The following sections describe ways to use these strategies effectively. Built-in functions Your three best friends in debugging are the built-in functions repr , type , and dir. Even when the bug in your program is a logic error, the symptom is often a wrong value getting passed around. Finding out what that value is and where it came from usually allows you to figure out the bug.

Here's a trivial case. What you might do next is check what price and qty are by using repr and type , as shown in the following example code. So where's repr? In interactive mode, if you just type the name, Python automatically uses repr. You need to actually type repr only when you're debugging in scripts.

Both price and qty are strings. In order to multiply them, you need to turn them into numbers. We discuss how to do this in Chapter Print statements and traceback logs When debugging, add print statements whenever you give a name to a value or manipulate something.

You'll quickly discover at what point the name takes on the wrong value. Warning Don't suppress tracebacks Python's information about errors or unusual conditions it encounters. If you want your program to continue after an error has occurred instead of quitting , log or print the traceback and go back later. Although print statements are useful in simple programs, wading through the output is difficult if you have a lot of them.

It's also difficult to selectively turn print statements on and off. The logging module directs your debugging output to a file for later perusal. To control the amount of output, just change the logging level. Comments To use comments for debugging, add lines to the code that print the values of various names throughout the program. Then append a comment like for debugging to these lines of code so you know to remove them later. Tip Using the comment character at the beginning of a line of code disables that line.

In some cases, disabling individual lines helps you track down which line of code is the source of a problem. Using a debugger A debugger lets you step through your code one line at a time or one code block at a time. It displays all the values Python keeps track of, showing exactly where values change. At the command prompt, type python -m pdb x. You'll see something like this: The 1 on the first line indicates the first line of the program. Pdb is the prompt. To run the current line of the program and go to the next line, type s.

Each time you press s which is short for "step" , you see the next line number and its code. In this example, you also see the result of the print statement on the first line. Pdb s This function creates a list. This process is considered a single step. When you want to check that the program is storing the correct values, type p and the name to see its value. We got this result after we'd stepped through the program ten times: Pdb p a [1, 2] Tip To see available commands while you run pdb, type help.

If the line is a function call, go to the first line inside the function. But if the line is a function call, run the whole function and go to the next line after the function call. Break points If you know that most of your program is working but you suspect a problem in one part, you can set a break point where you think the problem is.

To see the values your program is storing at this point, type p and the name whose value you want to see. The following example sets a break point at line 5 of our program, runs the program until it reaches the break point, and examines the values at that point. Note that the break occurs before Python runs line 5. Gretsky, tell the employees they can have internet games on their computer again.

Stringing Them Along Inside Python, a string literal is surrounded by quotation marks, which distinguish it from other kinds of data, such as integers or names.

You see the quotation marks when you type the name of a string in the interpreter. But when you print a string, the quotation marks don't appear.

The print statement uses str , which displays a "prettier" version. Chapter 2 has more details. The following sections describe several ways to quote strings and how to use special characters inside strings or how not to use them.

Just the quotes, ma'am You can surround a string with single, double, or triple quotes. Which you use depends on the string contents and formatting you want. Both mean "a string is inside. Likewise, if your text includes double quotes, it's easiest to make a string by surrounding it with single ones. Triple-scoop To make a string that prints exactly as you type it, use triple quotes, either single """ or double """.

A docstring is a short description of a code block, such as a function. Python's help function automatically formats and returns the text of the docstring when you ask for help on the code block. For more about docstrings, see Chapter Tip Triple quotes are also useful for surrounding text that has both single and double quotation marks.

These are commonly called escape codes. Tip It's easier to read strings that don't have escape characters within the code, so avoid them if you can. If you have text with both single and double quotes, consider using triple quotes to designate it as a string. You might want to do this when handling Windows pathnames, which include the backslash character. Tip Raw strings also simplify regular expression searches, which also use backslashes as special characters.

It's an error to end a raw string with a backslash because Python thinks you're using the backslash to escape the quote mark that ends the string. To type a string that ends with a backslash, you must use a regular string. You can add it to the raw string simply by typing it on the same line. We recommend this method for entering long strings because it's easy to read. What you type after you press Return counts as part of the same line. How a string looks inside Python To see how Python internally represents a string, type the name of the string and press Return.

These operators let you perform an operation and give the result to a name at the same time. They are very useful in loops because they make the assignment statement easy to read. You can't add a string and a number together—you must first convert the string to a number for example, by using the int or float functions.

Comparing strings When you're working with numbers, it's usually obvious what the smallest and largest numbers are. But it's less clear what smallest and largest mean when you're talking about characters. So it would also be correct to talk about one character coming "before" smaller or "after" larger another character in a numbered list of characters.

A is smaller than Z. Y and Z are both smaller than a. Because a string is a sequence data type, you can use it in a loop; that is, you can iterateover it. But there are very few reasons to do this. In fact, code that does this probably has a bug. Python doesn't have a built-in error or warning message for iterating over a string, but external debugging tools such as PyChecker often flag it as a bug.

The PyChecker tool looks for common problems in Python code. A few more methods for working with strings You use a string method to perform actions on a string. To use a string method, type the name of your string, a dot, and the method. Then inside parentheses, pass any parameters that the method needs. These tests return True or False Boolean results.

To test whether text is anywhere in a string, type the text you're searching for in quotation marks, followed by in and the name of the string. This example gives a name to a string and tests for the string 'goose' inside the string. Tip Python 2. In those versions, you can test for text in a string by using the find or count method. The startswith method works the same way but finds text at the beginning of a string.

The string methods work with both regular strings and Unicode strings see the upcoming section, "Unraveling Unicode". The string module versus the str type Early versions of Python implemented string operations as functions in the string module. In Python 2. The string module still works, but use of the string module usually indicates an old program except for string. Cat's Cradle: Indexing and Slicing Strings and other sequential data types are divided into pieces called elements that are stored in order in a sequence.

In a string, each character is one element. You manipulate the individual elements by using operations called indexing and slicing. An index number specifies the location of a particular element, and a range of index numbers specifies a slice of several elements. This section describes the basics of indexing and slicing.

You also find out some shortcuts and discover how to use slices to make copies of strings. But you can use slicing to make a new string based on part of an existing string. Basic syntax You use indexing to find an element of a sequence object such as a character in a string based on the element's index number. You use slicing to find a range of elements. Indexing To find an item corresponding to a particular index number, type the name of your string or other sequence object followed by an index number in brackets.

Note that the first index number is 0. Inside the brackets, you enter a slice expression: the beginning of the slice, a colon, and the end of the slice. In the example below, five elements are returned index numbers 7, 8, 9, 10, and Figuring out the tricks Following are some shortcuts you can use with slicing and indexing syntax.

If you use a number larger than the size of the sequence, Python raises an IndexError. This is called negative indexing. When indexing, the first index number, from the right, is -1, the next is -2, and so on—but the leftmost index is still 0. Figure Relationship of indexes, slice indexes, and elements in a sequence object.

When used with strings, this operator is sometimes called the interpolation operator. When we use the word formatting, we aren't referring to word processor—type formatting —changing fonts, colors, styles, and the like.

We mean specifying what happens when a value is inserted into a string. For example, we might specify how many digits to display to the right of a decimal point.

The interpolation operator also lets you insert data in specific places in a string. This means you can calculate your data in one part of your program and print it or save it to a file in another part. Each character stands for a particular type of data to be included in a string. You must type the formatting modifiers and code without spaces and use this order: 1.

A mapping key in parentheses described in "Formatting with a dictionary," later in this chapter. Conversion flags, so-called because they affect how some kinds of data are converted when they're included in the string. The minimum amount of space to allow for the data minimum field width —a positive integer. How many digits to include to the right of the decimal point of a decimal number precision —a dot. The formatting code The first and last of the preceding steps are required; the rest are optional.

Type your string up to the point where you want your data to go, like this: 2. Type print, followed by a formatting code for each item you want to include, like so: 2. If you remember to do this consistently, you'll be ahead in the debugging game. You use a mapping key to stand for the value to be used from the dictionary. Follow these steps to create a line of code that gets the value of the mathematical constant e from a dictionary and prints it as part of a string.

Type your string up to the point where you want to include your data, like so: 2. Type the formatting code so that the whole chunk of code looks something like this : 6. But what if you need to use Russian or Japanese? Python 2. Unicode strings work mostly the same way as regular strings.

Type u to specify a Unicode string and then start typing the string. Type the rest of the string and the ending quotation mark: 6. ASCII characters are encoded by using 7 bits of information, which allows for only 0— characters. That wasn't enough for non-English languages, accented characters, and other common symbols.

Enter Unicode. Unicode will eventually be able to encode every character set, including those for non-European languages, alphabets used by scholars, and mathematical and linguistic symbols. The locale also determines the default character encoding that Python uses. The encoded string must match that encoding. When you print a Unicode string, Python automatically tries to do this conversion so that you see the characters you expect.

A twisty maze of codes Unicode lets you process text by using only one code. But Unicode can't be used directly with character input and output, so you need to encode output and decode input. Beginners tend to think of Unicode as another encoding of the character set they are used to using. Thus, they think that they need to encode "regular" text into Unicode and decode Unicode into regular text. That's backward. Here's the correct way to think about it: When you start using Unicode, whatever regular character set you're using is a part of Unicode.

Therefore, you need to encode Unicode characters into your regular character set, and decode your regular character set into Unicode. Encoding, decoding, and other Unicode methods All the regular string methods also work with Unicode strings. A couple of methods apply especially to Unicode: encode and decode.

Follow these steps: 1. Create a Unicode string, like so: 2. Type the name of the string, a dot, encode, and in parentheses the encoding you want to convert to. Decoding a string into Unicode The decode method, new in Python 2. To decode a string into Unicode, follow these steps: 1. Create an encoded string, like so this string is encoded using UTF-8 : 2. Type the name of the string, a dot, decode, and in parentheses the encoding that the string currently uses.

When you use a Unicode string and a regular string together, the results are always Unicode. Don't touch me, Midas! Chapter 3 introduces the number types and their operators. This chapter gives you more information on integers, binary floating point numbers, and complex numbers, and provides guidance for using Python's augmented assignment operators.

It also introduces Python's built-in math modules, including the decimal module for doing true decimal arithmetic, and the random module for generating random numbers. Integrating Integers Integers are positive and negative whole numbers numbers without a value to the right of the decimal point.

We give you a brief overview of integers in Chapter 3; the following sections describe some finer points about Python's integers. But integers larger than a certain value 2,,,, to be exact take up more than 32 bits of memory. So Python uses a different mechanism to store them. Python represents long integers with the suffix L.

For now, if you're writing programs that manipulate very large integers, each version of Python handles integers a bit differently. Your results may vary depending on the version. If you're using Python 2. Avoiding unexpected results with integer division If you enter only integers when you do arithmetic, Python returns the results in integers. See the section, "Turning Python into a Calculator with decimal," later in this chapter, for details.

Floating Along The standard format for computers to store real numbers is called binary floating point, which is different from the format most people are used to. For example, if you type 0. For detail nuts only: The decimal numbers that can be represented accurately have a fractional component containing only sums of powers of two. For example, if you do a math operation with both integers and floats, Python converts the integers to floats and gives the result as a float.

Formatting floats If you don't want to look at weird numbers with 16 decimal places, use the str function to display the number as a string. But round requires you to specify a precision the number of digits to the right of the decimal point and defaults to a precision of 0 which removes all the digits to the right of the decimal point. This probably isn't what you want if you're working with decimal numbers! Size limits on floats Python's binary floating point numbers have a finite range.

Python stores binary floats using at most 17 decimal digits of accuracy. In addition, the largest float you can store is 1. The following code attempts to convert 10 1, to a float. A number doesn't equal itself plus 1, no matter how big it is! In Python, to specify an imaginary number, or the imaginary part of a complex number, append j to the number.

To separate the real or imaginary part of a complex number, type x. An "augmented" assignment statement has an extra feature—an addition or concatenation operation—built in. If you're trying to debug someone else's thousand-line program, you'll appreciate the simplicity!

These statements evaluate an object only once and change mutable objects in place; regular assignment evaluates an object twice and creates a new copy in the process. This can slow performance with large objects. Tip To import any of the math modules, type import followed by the name of the module. The cmath module also returns values for calculations such as the square root of a negative number. The math module treats such calculations as errors.

Many of the two modules' functions have the same names but work differently. The module name helps you keep track of which function you're using. Decimal numbers: The decimal module lets you work with decimal numbers rather than binary floating point numbers. See "Turning Python into a Calculator with decimal," later in this chapter. Random numbers: The random module includes tools for such tasks as generating random numbers and choosing randomly from several elements. For a fun introduction to the tricks up the sleeve of the random module, see Chapter Turning Python into a Calculator with decimal The decimal module, new in Python 2.

If you're writing applications that require control over precision and rounding such as financial software or statistics modules , this module is for you. Its results also match calculations done by hand math educators take note! Like other numbers, decimal numbers are immutable. They must be converted to strings first. The first item in the tuple is 0 for positive or 1 for negative. The second item is another nested tuple containing the digits of the number, one element for each digit.

The third item is a positive or negative integer specifying the exponent. Decimal numbers work with Python's regular math functions.

Compound data types group collections of data. Python has several kinds of compound data types. Lists and tuples are sequence types because each element of data is numbered sequentially, starting with 0.

Sequence types support operations called indexing and slicing for working with individual elements or subsets of elements. You can find out about indexing and slicing in Chapter 6. A sequence data type is good when you want to operate on all the elements in a collection or when the order of elements in a collection is important.

In contrast, the dictionary data type—a mapping type—is for random access to elements, and a set is for comparing collections of objects. Dictionaries and sets are covered in Chapter 9. This chapter shows you the syntax for lists and tuples, when to use them, how to work with elements inside them, how to use them in loops, and how to avoid some of the common errors programmers make when working with them.

Introducing Lists and Tuples The following sections describe the features and syntax of lists and tuples and explain when to use each. What a list is A list is a mutable data type, which means you can change the contents of a list without creating a new list. The elements of a list can be of different data types. A single list can contain numbers, strings, other lists, tuples—and even functions and classes. In Python, a list literal the actual data, not a name referring to the data is defined by square brackets surrounding zero or more elements.

Elements are separated by commas. Tuples are different from lists because tuples are immutable. If you want to change the contents of a tuple, you must create a new tuple that has the new content you want.

Warning If a tuple contains a mutable element such as a list or dictionary , the mutable element can be modified. However, some of the obvious ways of changing the mutable element will cause errors because Python will attempt to modify the tuple. We recommend that you avoid changing mutable elements in tuples. Tuples don't include a lot of special methods, the way strings and lists do. But tuples do include methods that support standard Python operators.

For example, you can add tuples, check whether an item is inside a tuple, slice elements in a tuple, compare a tuple to other data, find a tuple's length, and so on. Many Python functions, such as the time and date functions, return tuples. Tuples are often better than lists for information that you don't want to change, for two reasons: They use less memory, and because they're immutable they won't change unexpectedly.

Lists are often better for information you want to change because there are more ways of manipulating them. For example, if you're accessing a database, the fields of a record might be returned as a tuple, but the records themselves should be returned as a list.

Therefore the overall database would be a list of tuples. You can and usually should use parentheses when creating a tuple, but you don't have to. Below are examples of tuples. Tip Because the comma is overloaded that is, it does more than one thing in Python and because it has low precedence that is, most other operations are evaluated before comma operations , it's usually a Good Idea to add parentheses to make it clear that you are using a tuple.

Comparing sequence objects Sequence objects such as lists can be compared to other objects of the same data type. A comparison tells you whether the objects are equal or whether one is smaller than the other. Chapter 6 has more information about character order.

Table shows the results of comparisons between sequences. The rules for comparing objects of different types may change in future versions of Python. You can't concatenate a list and a tuple. The former works slightly faster and is easier to read. You can turn other data into lists, count items in lists, sort lists in various orders, and use indexing and slicing to change, add, delete, and move individual list items.

Functions that work with or create lists The list function creates a copy of a list. It also turns any other sequence object or iterable into a list. An iterable is an object whose elements can be retrieved one at a time. The method names are attributes of the object. List method syntax To call a list method, type the list name, a dot, the method name, and parentheses.

In the parentheses, pass any arguments the method needs. Some methods don't require or use arguments. This method changes the list in place. It returns None. This example counts the number of times the string 'apple' appears. If the iterable is a string, each character is added individually. This example adds each character of the string 'pear'. It raises a ValueError if the item isn't found. This example removes the first 'apple' string.

Indexing and slicing operations on lists and tuples work mostly the same way that they do with strings. Here's a quick review of how index numbers work.

For more about indexing and slicing, see Chapter 6. This example shows the items at index 0 and 1 of the list x. This example shows the items at index -1 and This example shows that slice contains just one element. You can change a list by using indexing and slicing. With a tuple or a string, you need to give a new name to the changed object or reassign the same name. Retrieving items from a list with slicing Following is a brief review of slicing syntax.

You can find more information in Chapter 6. It defaults to 0. It defaults to the last item of the sequence. To access the last sequence item in a slice, if you don't know the length of the sequence, leave the index blank.

The step defaults to 1. This is because slices point between elements. So [] retrieves the first and second elements. The section, "List references that unexpectedly change," later in the chapter, has more on shallow copying. The following example code creates a list of numbers and then, using slice syntax, selects and displays all the even-numbered items.

This replaces whatever is already at that index number. Assigning numbers and strings to slices If you assign to a slice, you must assign an iterable. This means two things: 1. You can't assign a number to a slice. Traceback most recent call last : 5. TypeError: can only assign an iterable 7. If you assign a string to a slice, each letter becomes a separate list item. Type the list name and then, in square brackets, type the index number, like this: 2. Assigning numbers and strings to slices".

To assign items to a list slice, follow these steps: 1. Type the name of the list and, in brackets, type the slice notation, like this: 2. L[] 3. If the item isn't in the list, it raises a ValueError. This example deletes two items. The default index number for pop is the last item in the list. It's easy to lose track of how the list is changing. An exception is the use of pop in a while loop to remove all list elements one by one. List references that unexpectedly change Because lists are mutable, you can change them without making a copy.

But if you reference a single list from several places in your code, it might change when you aren't expecting it to. The new container continues to refer to the original lists. The following example illustrates shallow copying. To do so, import the copy module and use the copy.

In this example, when you copy the food list to the larder list by using the deepcopy function, changing the contents of one of the lists in food doesn't change the contents of larder. They return None. Don't give the result a name. But the value of x doesn't change because x only contains copies of the elements of mylist.

For example, avoid using loops that delete elements from the beginning of a list del mylist[0] or mylist. Populating a list with elements before you need the list isn't necessary, and it might even waste memory. Building Lists, Stacks, and Queues This section describes two often-used list tasks: building a list one element at a time and building stacks and queues. Building lists incrementally Because lists are mutable, you can build them one element at a time. It is often useful to build lists from other iterable objects or to combine multiple lists.

Warning If you're iterating over a list in a for loop, it's best not to add elements to or delete elements from that list—doing so can introduce errors. It's safer to use code like the above example to build a new list and then change the elements of the new list. See Chapter 16 to find out about this advanced feature. It returns a list of tuples that associates the items in one sequence with the corresponding items in another sequence. It also truncates the resulting list to the length of the shortest sequence.

Stacks and queues are not Python objects, but you can write code in which a list behaves like a stack or a queue. A stack is like a spring-loaded plate dispenser where the last item on is the first item off this is also called "last in, first out" order, which is inscribed in the Great Book of Geeky Acronyms as "LIFO".

A queue, as folks familiar with British English know, is like a line at a store checkout counter: The first person in is the first served also called "first in, first out," or "FIFO".

Adding items to a stack To add an item to the top of a stack, use append. To retrieve all the items, use pop in a while loop. Use append to add an item to the end of the queue. Use pop 0 in a while loop to retrieve an item from the front of the queue, like this: 3. We cover converting other objects to tuples, several ways of creating tuples, using tuples to swap values, and efficiently giving names to individual items in tuples. Tuple packing If you type some names separated by commas, you create a tuple.

This is called tuple packing. It works on either side of an assignment statement. This example creates a tuple containing four strings. Tuple unpacking is useful because many functions in Python, such as the zip function described in the previous "Building lists incrementally" section, return tuples. With tuple unpacking, you can easily get at the individual items in these tuples. To unpack a tuple, just assign multiple names on a single line. Put the names you want to unpack into on the left side of the assignment statement and put the tuple on the right side.

You need one name for each item in the tuple. Using a tuple to swap values Because of the special way assignments work with tuples, tuples are the Pythonic way of swapping values.

But consider using sets if you are using Python 2. See "Setting Them Up," later in this chapter. STUFF You can also use a list in this case, but a dict is more memory-efficient, which often makes things faster. A dictionary's elements the items it contains are key:value pairs. In contrast, lists and tuples store data by using numeric indexes they are sequence data types and support indexing and slicing.



0コメント

  • 1000 / 1000