Menu
Home
Log in / Register

 
Home arrow Computer Science arrow Python Programming Fundamentals
< Prev   CONTENTS   Next >

3.3 Lists

A list in Python is any sequence of values surrounded by square brackets (i.e. [ ]). So for instance [0, 1, 2, 3] is a list. So is ['a', 1,'b', 4.2]. Lists are any sequence of values inside square brackets. The items of the list can be of different types, although it is quite common for all values in a list to be of the same type. The list type is called list in Python as you might expect.

A list is a sequence too. A list can be iterated over using a for loop just like a string. Each element of the list is used to execute the body of the for loop once. Chapter 11 contains a table that outlines the methods and operators that apply to lists. There are several operations on sequences that are useful. For instance, len(s) returns the length of a sequence (the number of elements in the sequence). We can concatenate two

sequences using +. So writing s + t returns a new string which is the juxtaposition of the strings referenced by s and t. We can get part of a sequence by slicing it. A slice is one or more contiguous elements of a sequence. It is created by using brackets and a colon. For instance, if s refers to the string “how are you?”, then s[0:3] is the string “how” and s[4:7] is the string “are”. You can even get a slice starting at the end of a sequence. So, s[−4:] gives you the last four items of a sequence, the string “you?” in this case. You can learn more about slicing in Chaps. 10 or 11. The length function, concatenation operator, and slicing apply to either strings or lists since they apply to

all types of sequences in Python.

Practice 3.6 Write a for loop that prints the following output.

0

1

2

3

4

The list of integers starting from 0 and going to n − 1 is so useful there is a function in Python that we can use to generate such a list. It is called range. The range function can be called on an integer, n, and it will generate a list of integers from 0 to n − 1. For instance, range(5) generates the list [0, 1, 2, 3, 4].

The range function can be used to generate other ranges of integers, too. In general

the range function is called by writing range([start,]stop[,increment]). For example,

range(10, 110, 10) generates the list [10, 20, 30, 40, 50, 60, 70, 80, 90, 100] and

range(10, 0,1] generates the list [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]. In Sect. 1.13 we learned that writing s[0] referred to the first character in the string s. s[1] refers to the second character. Writing s[−1] returns the last element of s. The indexing operations apply to all sequences, not just strings. Using indexing and a for loop together we can write

some interesting code.

Example 3.5 This example uses indexing to print each of the characters in astring on separate lines. The output from this program is exactly the same asthe output from Example 3.4. Contrast this code to the code that appeared inExample 3.4.

1 s = i n p u t ("Please type some characters and press enter:")

2 f o r i i n r a n g e ( l e n (s)):

3 p r i n t (s[i])

4 p r i n t ("Done")

Notice the use of the len function inside the call to the range function. When we wish to go through all the elements of a list and we need an index into that list, the len function can be used along with range to generate the proper list of integers for the indices of the list.

Practice 3.7 Write a program that prints out the characters of a string in reverse order. So, if “hello” is entered, the program prints:

o

l

l

e

h

To accomplish this, you must use a for loop over the indices of the list since you cannot directly go backwards through a sequence with a for loop. However, you can generate a list with the indices going from the last to first index.

Python includes a few methods that make it much easier to process strings in your programs. One of these methods is called split. The split method splits a string into words. Each word is defined as a sequence of characters separated by whitespace in your string. Whitespace are blanks, tabs, and newline characters in your strings. The split method splits a string into a list of strings.

Example 3.6 Contrast the code found here with the code in Example 3.4. Notice that the for loop contains s.split() instead of just s.

1 s = i n p u t ("Please type some characters and press enter:")

2 f o r word i n s.split ():

3 p r i n t (word)

4 p r i n t ("Done")

If the user enters “how are you?” the output is:

how

are

you?

Done

Practice 3.8 You can see what the split method does by setting some variableto the result of s.split(). For instance, the second line could be:splitWords = s.split ()Modify the code to add this line and use splitWords in the for loop.Run the codein Example 3.6 using the debugger. Step into and over the code and watch theword and splitWords variables. Run the program several times with differentinput and make note of what splitWords ends up containing.What is the type of the value that s.split() returns? What does the for loopiterate over?

Another useful operator on sequences is the in operator. This operator makes it possible to check to see if an item is in a sequence. For a string, this means you can ask, “Is a character in this string?”. For a list it means you can ask if an item is in a list.

Example 3.7 Consider this code that determines if you like something similar to Sophus Lie. The in operator let's you find an item in a list and returns True if it does and False otherwise.

1 activity = i n p u t ("What do you like to do?")

2 liesActivities = ["math", "hike", "walk", "gymnastics"]

3 i f activity i n liesActivities:

4 p r i n t ("Sopus Lie like to do that , too!")

5 e l s e :

6 p r i n t ("Good for you!")

 
Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >
 
Subjects
Accounting
Business & Finance
Communication
Computer Science
Economics
Education
Engineering
Environment
Geography
Health
History
Language & Literature
Law
Management
Marketing
Philosophy
Political science
Psychology
Religion
Sociology
Travel