Python Fundamentals – List Manipulation
INTRODUCTION
Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any type. The values in a list are called elements or sometimes items. Lists are more general than strings.
- Strings are always sequences of characters, whereas lists can contain values of any type. Lists can contain values of mixed data types. A single list can contain numbers, strings, or other lists.
- Unlike strings, which are immutable, it is possible to change individual elements of a list. Lists are mutable, which means that items in a list can be modified by assigning new values.
- Like string indices, list indices start at 0, and lists can be sliced, concatenated and so on.
- List is a sequence that can be indexed into, and that can grow and shrink by adding elements and deleting elements from the list.
CREATING LISTS
There are several ways to create a new list; the simplest is to enclose the elements in square brackets ([ and ]). Following are some lists in Python:
››› L1 = [10, 20, 30, 40] # list of 4 integer elements ››› L2 = ["Raj", "Govind", "Abdul"] # list of 3 strings ››› L3 = [1, 1.5, 2.5, 7] # list of numbers integer and float ››› L4 = ['a', 'b', 'c'] # list of characters ››› L6 = [] # list with no memebers i.e. empty list ››› L7 = ['Orange', 2.0, 5, [10,20]] # nested list
A list within another list is called nested list. Although a list can contain another list, the nested list still counts as a single element. So the length of list L7 is four. A list that con¬tains no elements is called an empty list; you can create one with empty brackets, [] as shown above. You can also create long lists containing many elements by split the list across several lines. Note that opening and closing square brackets appear just in the beginning and end of the list.
evennum = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]
You can also create lists of single characters or digits using keyboard input. For example,
list1 = list(raw input('Enter elements of list: ')) Enter elements of list: 2468 ››› list1 ['2', '4', '6', '8']
Notice we have entered integers, but the datatype of all characters entered is string. To enter a list of integers we use eval() method as given below:
list2= eval(raw_input("Enter list: " )) print list2
A string is a sequence of characters and a list is a sequence of values, but a list of char¬acters is not the same as a string. To convert from a string to a list of characters, you can use list:
››› s = 'hello' ››› t = list(s) ››› print t ['h', 'e', 'l', 'l', 'o' ]
Because list is the name of a built-in function, you should avoid using it as a variable name.
The list function breaks a string into individual letters. If you want to break a string into words, you can use the split method:
››› s = 'work is worship' ››› t = s.split() ››› print t ['work', 'is', 'worship']
Concept of Mutable Lists
Lists are mutable. That means that the value of an item in a list can be modified with an assignment statement. In other words, you can change the contents of a list without cre-ating a new list. Strings, on the other hand, cannot be changed or modified.
››› num = [17, 12, 18] ››› num[l] = 5 ››› print num [17, 5, 18]
The first element of num, which used to be 12, is now changed to 5. You can think of a list as a relationship between indices and elements. This relationship is called a mapping; each index “maps to” one of the elements.
ACCESSING LISTS
Lists are a container data type that acts as a dynamic array. In other words, a list is a sequence that can be indexed into and can grow and shrink. List elements have index numbers. Indexing and slicing operations on lists work mostly the same way that they do with strings. Working from left to right, the first element has the index 0, the next has the index 1, and so on.
Indexing
We can also say that list data type is a container that holds a number of elements in a given order. For accessing an element of the list, indexing is used. This example shows the items at index 0 and 1 of the list x.
x = ['apple', 'banana', 'pear'] ››› x [0] 'apple' ››› x[l] 'banana'
Working from right to left, the first element has the index -1, the next one -2, and so on, but the leftmost element is still 0. This example shows the items at index -1 and -2.
››› x[-l] 'pear' ››› x[-2] 'banana'
The literal representation of a list is square brackets containing zero or more items sepa-rated by commas.
An individual element of a list can also accessed through their indexes. For example,
››› ch = ['1','o','w','e','r'] ››› ch [0] '1' ››› ch [4] ' r' ››› ch[-l] ' r' ››› ch[-5] '1'
Note that while accessing individual elements, if you give index outside the legal indices Python will raise IndexError as shown below:
››› ch[5] Traceback (most recent call last): File "<pyshell#4>"., line 1, in <module> ch [5] IndexError: list index out of range
Slicing
We know that a slice of a list is its sub-list. Just as you use indexing to access individual elements, you can use slicing to access ranges of elements. You do this by using two indices, separated by a colon (:). Slicing is very useful for extracting parts of a sequence. The numbering here is very important. The first index is the number of the first element you want to include.
Slices are treated as boundaries, and the result will contain all the elements between boundaries. Its syntax is:
seq = L [start: stop: step]
Where start, stop and step all three are optional. If you omit first index, slice starts from 0 and omitting of stop will take it to end. Default value of step is 1.
You supply two indices as limits for your slice, where the first is inclusive and the sec¬ond is exclusive.
Consider the following:
››› numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ››› numbers[3:6] [4, 5, 6] ››› numbers [0:1] [1]
Let’s say you want to access the last three elements of numbers.
››› numbers[7:10] [8, 9, 10]
Now, the index 10 refers to element 11 which does not exist, but is one step after the last element you want.
In a regular slice, the step length is one, which means that the slice moves from one ele-ment to the next, returning all the elements between the start and end:
››› numbers[0:10 :1] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In the above example, you can see that the slice includes another number, the step size, made explicit.
If the step size is set to a number greater than one, elements will be skipped. For exam-ple, a step size of two will include only every other element of the interval between the start and the end:
››› numbers[0:10:2] [1, 3, 5, 7, 9] numbers [3:6:3] [4]
You can use the shortcuts, for example, if you want every fourth element of a sequence, you need to supply only a step size of four:
››› numbers!::4] [1, 5, 9]
The step size can’t be zero that wouldn’t get you anywhere but it can be negative, which means extracting the elements from right to left:
››› numbers[8:3:-1] [9, 8, 7, 6, 5] ››› numbers [10:0:-2] [10, 8, 6, 4, 2] ››› numbers [0:10:-2] [] ››› numbers[::-2] [10, 8, 6, 4, 2] ››› numbers [5::-2] [6, 4, 2] ››› numbers [:5:-2] [10, 8]
As you can see, the first limit (the leftmost) is still inclusive, while the second (the right-most) is exclusive. When using a negative step size, you need to have a first limit (start index) that is higher than the second one.
Traversing
The sequential accessing of each element in a list is called traversing. This can be done in many ways as shown in following Examples.
Example 1
# List traverse numbers = [1 ,2, 3, 4, 5, 6, 7, 8, 9, 10] i = 0 while i < 10: print numbers [i], i = i + 1 RUN ››› 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ›››
Figure 16.1 List traverse using while loop
Example 2
# Traversing list using for loop numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] for i in numbers: print i, RUN ››› 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ›››
Figure 16.2 Traversing list using for loop
Example 3
# Traversing list using while loop and len function numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] i = 0 while i < len(numbers): print numbers [i], i += 1 RUN ››› 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ›››
Figure 16.3 Traversing list using while loop and len function
Example 4
# Traversing list and printing even numbers numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] i=1 while i < len(numbers): print numbers[i], i += 2 RUN ››› 2 4 6 8 10 ›››
Figure 16.4 Traversing list and printing even numbers
Program to print elements of a list with their positive and negative indexes
Example 5
# Program to print elements of list along with their indexes ch = ['1', 'o', 'w' , 'e' , 'r'] length = len(ch) for i in range(length): print "At positive index", i, "and negative index", (i- length), "element is : ", ch[i] RUN ››› At positive index 0 and negative index -5 element is : 1 At positive index 1 and negative index -4 element is : o At positive index 2 and negative index -3 element is : w At positive index 3 and negative index -2 element is : e At positive index 4 and negative index -1 element is : r ›››
Figure 16.5 Program to print elements of list along with their indexes
LIST OPERATIONS
There are several operations that are applicable to lists. These are discussed in the fol-lowing sections:
Joining Lists
Joining list means to concatenate (add) two lists together. The plus (+) operator, applied to two lists produces a new list that is a concatenation of two lists:
››› a = [1, 2, 3] ››› b = [4, 5, 6] ››› c = a + b ››› print c [1, 2, 3, 4, 5, 6]
The + operator when used with lists requires both the operands to be of list types other wise it will produce error. For example,
››› li = [10, 20, 30] ››› li + 2 ››› li + "xyz"
Repeating Lists
Multiplying a list by an integer n creates a new list that repeats the original list n times. The * operator repeats a list a given number of times.
››› [0] * 4 [0, 0, 0, 0] ››› [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]
The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three times.
Slicing Lists
The slice operator also works on lists. If you omit the first index, the slice starts at the beginning. If you omit the second, the slice goes to the end. So if you omit both, the slice is a copy of the whole list.
››› t = ['a', 'b', ' c', 'd', 'e', 'f'] ››› t[l:3] ['b', 'c'] ››› t [ 14] ['a', 'b', 'c', 'd'] ››› t [3 : ] I'd', 'e', 'f'] ››› t [:] ['a', 'b', 'c', 'd', 'e', 'f']
A slice operator on the left side of an assignment can update multiple elements:
››› t = ['a', 'b', 'c', 'd', 'e', 'f'] ››› t[l:3] = ['x', 'y'] ››› print t ['a', 'x', 'y', 'd', 'e', 'f'3
Comparing Lists
Tests whether the contents of two or more lists are the same. The comparison operators can be used to compare lists.
››› [11, 22] == [11, 22] ››› [11, 22] < [11, 33]
OBJECTS AND VALUES
If we execute these assignment statements:
a = ‘apple’
b = ‘apple’
We know that a and b both refer to a string, but we don’t know whether they refer to the same string. There are two possible states:
(a) In first case, a and b refer to two different objects that have the same value.
(b) In the second case, they refer to the same object.
To check whether two variables refer to the same object, you can use the is operator.
››› a = 'apple' ››› b = 'apple' ››› a is b True
In this example, Python only created one string object, and both a and b refer to it.
But when you create two lists, you get two objects:
››› a = [1, 3, 5] ››› b = [1, 3, 5] ››› a is b False
In this case we would say that the two lists are equivalent, because they have the same elements, but not identical, because they are not the same object. If two objects are iden-tical, they are also equivalent, but if they are equivalent, they are not necessarily identi-cal.
Aliasing
A circumstance where two or more variables refer to the same object is called aliasing. If a refers to an object and you assign b = a, then both variables refer to the same object:
››› a = [1, 3, 5] ››› b = a ››› b is a True
The association of a variable with an object is called a reference. In this example, there are two references to the same object.
An object with more than one reference has more than one name, so we say that the object is aliased.
If the aliased object is mutable, changes made with one alias affect the other:
››› b [1] =7 ››› print a [1, 7, 5]
LIST FUNCTIONS AND METHODS
Python provides methods that operate on lists. For example, append adds a new element to the end of a list, extend takes a list as an argument and appends all of the elements, sort arranges the elements of the list from low to high, pop modifies the list and returns the element that was removed.
Every list object that you create in Python is actually an instance of List class. The syntax of using it is discussed below:
<listObject>.<method name>()
len()
The built-in len() function is used to get the length of list.
››› list = ['a', 'b', 'c', 'd'] ››› len(a) 4
It is possible to nest lists (create lists containing other lists), for example:
››› q = [2, 3] ››› p = [1, q, 4] ››› len(p) 3
append()
To add an item to the end of a list, use the append() method. This method changes the list in place. This example adds the string ‘apple’ to a list:
››› basket = ['apple', 'banana', 'orange'] ››› basket.append('apple') ››› basket ['apple', 'banana', 'orange', 'apple'] ››› items = [111, 222, 333] ››› items.append(444) ››› items [111, 222, 333, 444]
count()
To find out the number of times a value occurs in a list, use the count(value) method.
››› basket = ['apple', 'banana', 'orange', 'apple'] ››› basket.count('apple') 2
extend()
To add the items in one list to an existing list, use the extend() method. If the iterable is a string, each character is added individually.
This example adds each character of the string ‘pear’.
››› x = ['apple', 'apple', 'banana', 'orange'] ››› x.extend('pear') ››› x ['apple', 'apple', 'banana', 'orange', 'p', 'e', 'a', 'r'] ››› a = [11, 22, 33,] ››› b = [44, 55] ››› a.extend(b) ››› a [11, 22, 33, 44, 55]
insert()
To insert an item into a list, use insert() method. This example inserts an item at the beginning of a list:
››› items [111, 222, 333, 444] ››› items.insert(0, 1) ››› items [1, 111, 222, 333, 444] ››› numbers = [1, 2, 3, 5, 6, 7] ››› numbers.insert(3, 'four') ››› numbers [1, 2, 3, 'four', 5, 6, 7]
pop()
The pop() method on a list returns the “rightmost”, i.e., the last item from a list and removes that item from the list. You can also push items onto the right end of a list and pop items off the right end of a list with append() and pop(). This enables us to use a list as a stack like data structure.
››› items = [111, 222, 333, 444, ] ››› items [111, 222, 333, 444] ››› items.append(555) ››› items [111, 222, 333, 444, 555] ››› items.pop() 555 ››› items [111, 222, 333, 444] ››› a = [11, 22, 33, 44, ] ››› b = a.pop() ››› a [11, 22, 33] ››› b 44 ››› b = a.pop() ››› a [11, 22] ››› b 33 ››› x = [1, 2, 3] ››› x.pop() 3 ››› x [1, 2] ››› x.pop(0) 1 ››› x [2]
The pop() method is the only list method that both modifies the list and returns a value (other than None). Using pop, you can implement a common data structure called a stack. A stack like this works just like a stack of plates. You can put plates on top, and you can remove plates from the top. The last one you put into the stack is the first one to be removed. (This principle is called Last-In, First-Out or LIFO).
remove()
The remove() method is used to remove the first occurrence of a value.
››› x = ['to', 'be', 'or', 'not', 'to', 'be'] ››› x.remove('be') ››› x ['to', 'or', 'not', 'to', 'be'] ››› x.remove('bee') Traceback (innermost last): File "<pyshell#3>", line 1, in ? x.remove('bee') ValueError: list.remove(x): x not in list
As you can see, only the first occurrence is removed, and you cannot remove something (in this case, the string ‘bee’) if it isn’t in the list to begin with. It’s important to note that this is one of the “non-returning in-place changing” methods. It modifies the list, but returns nothing (as opposed to pop).
reverse()
The reverse() method reverses the elements in the list.
››› x = [1, 2, 3] ››› x.reverseO ››› x [3, 2, 1]
sort()
The sort() method is used to sort lists in place. Sorting ‘in place’ means changing the original list so its elements are in sorted order, rather than simply returning a sorted copy of the list:
››› x = [4, 6, 2, 1, 7, 9] ››› x.sort() ››› x [1, 2, 4, 6, 7, 9]
The confusion usually occurs when users want a sorted copy of a list while leaving the original alone.
››› x = [4, 6, 2, 1, 7, 9] ››› y = x.sortO # Don't do this! ››› print y None
Because sort modifies x but returns nothing, you end up with a sorted x and a y containing None. One correct way of doing this would be to first bind y to a copy of x, and then sort y, as follows:
››› x = [4, 6, 2, 1, 7, 9] ››› y = x [ : ] ››› y. sort () ››› x [4, 6, 2, 1, 7, 9] ››› y [1, 2, 4, 6, 7, 9]
x[:] is a slice containing all the elements of x, effectively a copy of the entire list.
Example 6
# Working with List a = [4, 2.5, 7, 8, 4,7.5] print "Original list ", a a. insert(2, -1) print "list after inserting value -1, ", a a.append(33) print "list after appending value 33, ", a print "index position of value 33 is, ", a.index(33) a.remove(33) print "list after removing value 33, ", a a.reverse() print "list after reversing, ", a a.sort() print "list after sorting, ", a, RUN ››› Original list [4, 2.5, 7, 8, 4, 7.5] list after inserting value -1, [4, 2.5, -1, 7, 8, 4, 7.5] list after appending value 33, [4, 2.5, -1, 7, 8, 4, 7.5, 33] index position of value 33 is, 7 list after removing value 33, [4, 2.5, -1, 7, 8, 4, 7.5] list after reversing, [7.5, 4, 8, 7, -1, 2.5, 4] list after sorting, [-1, 2.5, 4, 4, 7, 7.5, 8] ›››
Figure 16.6 Working with List
SOLVED EXERCISE
Question 1.
What is the significance of list?
Answer:
A list is used to collect a number of values or variables in an ordered sequence. A list element can be any Python object, including numbers, strings, functions, and other lists.
Question 2.
What is the difference between string and list?
Answer:
Difference between string and list:
(a) Strings are always sequences of characters, whereas lists can contain values of any type, i.e, Lists can contain values of mixed data types. A single list can contain numbers, strings, other lists.
(b) Unlike strings, which are immutable, it is possible to change individual ele-ments of a list, i.e., Lists are mutable, which means that items in a list can be modified by assigning new values.
Question 3.
Lists are mutable. Comment.
Answer:
Lists are mutable. That means that the value of an item in a list can be modified with an assignment statement. Strings, on the other hand, cannot be changed.
Question 4.
Why are Python Lists called dynamic arrays?
Answer:
Lists are dynamic arrays. They are arrays in the sense that you can index items in a list (for example “mylist[3]”) and you can select subranges (for example “my- list[2:4]”).
They are dynamic in the sense that you can add and remove items after the list is created. .
Question 5.
How will you extract different parts of a list. Explain with an example.
Answer:
Python has a nice syntax for extracting parts of a list structure. Such parts are known as sublists or slices:
A[i:] is the sublist starting with index i in A and continuing to the end of A:
››› A = [2, 3.5, 8, 10] ››› A [2 : ] [8, 10]
A[i:j] is the sublist starting with index i in A and continuing up to and including index j-1. Make sure you remember that the element corresponding to index j is not included in the sublist:
››› A[1:3] [3.5, 8]
A[:i] is the sublist starting with index 0 in A and continuing up to and including the element with index i-1:
››› A[:3] [2, 3.5, 8]
A[l:-1] extracts all elements except the first and the last (recall that index -1 refers to the last element), and A[:] is the whole list:
››› A[1:-1] [3.5, 8] ››› A[:] [2, 3.5, 8, 10]
Question 6.
What is an empty list in Python?
Answer:
A list that contains no elements is called an empty list; you can create one with empty brackets, [].
Question 7.
How list indices work in Python?
Answer:
List indices work the same way as string indices:
(a) Any integer expression can be used as an index.
(b) If you try to read or write an element that does not exist, you get an IndexError.
(c) If an index has a negative value, it counts backward from the end of the list.
Question 8.
Explain working of + and * operators in a list.
Answer:
The + operator concatenates lists:
››› a = [1,2, 3]
››› b = [4,5, 6]
››› c = a + b
››› print c
[1, 2,3,4, 5, 6]
Similarly, the * operator repeats a list a given number of times:
››› [0] * 4
[0, 0,0, 0]
››› [1, 2, 3] * 3
[1, 2,3,1,2, 3,1,2,3]
The first example repeats [0] four times. The second example repeats the list [1, 2, 3] three times.
Question 9.
What happens when you do following with the list:
(a) If you omit the first index.
(b) If you omit the second.
(c) If you omit both.
Answer:
(a) If you omit the first index, the slice starts at the beginning.
(b) If you omit the second, the slice goes to the end.
(c) If you omit both, the slice is a copy of the whole list.
Question 10.
How append() method differs with extend() method?
Answer:
append() method adds a new element to the end of a list:
››› t = ['a', 'b', 'c'] ››› t.append('d') ››› print t ['a', 'b', 'c, 'd']
extend() method takes a list as an argument and appends all of the elements:
››› t1 = ['a', 'b', 'c'] ››› t2 = ['d', 'e'] ››› t1.extend(t2) ››› print t1 ['a', 'b', 'c', 'd', 'e']
This example leaves t2 unmodified.
Question 11.
Explain count() method with example.
Answer:
The count method counts the occurrences of an element in a list:
››› ['to', 'be', 'or', 'not', 'to', 'be'].count('to') 2
Question 12.
Why is index() method used?
Answer:
The index() method is used for searching lists to find the index of the first occurrence of a value:
››› knights = ['We', 'are', 'the', 'knights', 'who', 'say', 'ni'] ››› knights.index('who'). 4
Question 13.
What is aliasing? Explain with an example.
Answer:
A circumstance where two or more variables refer to the same object is called alias-ing. If variable a refers to an object and you assign b = a, then both variables refer to the same object:
››› a = [1, 3, 5] ››› b = a ››› b is a True
Question 14.
What do you mean by sequence?
Answer:
A sequence is an ordered collection of items, indexed by positive integers. It is combination of mutable and non-mutable data types. Three types of sequence data type available in Python are strings, lists and tuples.
Question 15.
What is indexing?
Answer:
All elements in a sequence are numbered from zero and upwards. You can access them individually with a number. This is called indexing. You use an index to fetch an element. All sequences can be indexed in this way. When you use a negative index, Python counts from the right; that is, from the last element. The last element is at position-1.
Question 16.
Write a program that asks you for a year, a month (as a number from 1 to 12), and a day (1 to 31), and then prints out the date with the proper month name.
Answer:
# Print out a date, given year, month, and day as numbers months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' . ] # A list with one ending for each number from 1 to 31 endings = ['st', 'nd', 'rd'] + 17 * ['th'] \ + ['st', 'nd', 'rd'] + 7 * ['th'] \ + ['st'] year = raw_input('Year: ') month = raw_input('Month (1-12): ') day = raw_input('Day (1-31): ') month_number = int(month) day_number = int(day) # Remember to subtract 1 from month and day to get a correct index month name = months[month_number-1] ordinal = day + endings[day_number-1] print month_name + ' ' + ordinal + ', ' + year RUN ››› Year: 2 013 Month (1-12): 12 Day (1-31): 11 December 11th, 2013
Figure 1 Program for Q16
Question 17.
Write a program to print domain name using slice operation.
Answer:
# Split up a URL of the form http://www.something.com url = raw_input('Please enter the URL: ') domain = url [11:-4] print "Domain name: " +domain RUN ››› Please enter the URL: http://www.myschool.org Domain name: myschool ›››
Figure 2 Program for Q17
Question 18.
Write a program that reads in a user name and checks the entered password against a database (a list) that contains pairs of names and password. If the name/password pair is found in the database, the string ‘Access granted’ is printed otherwise “Access denied” is printed.
Answer:
# Check a user name and password database = [ ['Ajay', '1111'], ['Suman', '2222'], ['Abhishek', '3333'], ['Vivek', '4444'] ] ’ username = raw_input('User name: ') password = raw_input('Password: ') if [username, password] in database: print 'Access granted' else: print 'Access denied' RUN ››› User name : Vivek Password: 4444 Access granted. ››› ››› User name: Mona Password: 5555 Access denied. ›››
Figure 3 Program for Q18
Question 19.
Write a program to print average of entered number using two different methods.
Answer:
total = 0 count = 0 while True : inp = raw_input('Enter a number: ') if inp == 'done' : break value = float(inp) total = total + value count = count + 1 average = total / count print 'Average:' , average ››› Enter a number: 5 Enter a number: 7 Enter a number-: 8 Enter a number: done Average: 6.66666666667 ›››
Figure 4 Program for Q19
Averaging with a list numlist = list() while True : inp = raw_input('Enter a number: ') if inp == 'done' : break value = float(inp) numlist.append(value) average = sum(numlist) / len(numlist) print 'Average:', average ››› Enter a number: 5 Enter a number: 8 Enter a number: 9 Enter a number: 8 Enter a number: 9 Enter a number: done Average: 7.8 ›››
Figure 4 Program for Q19
Question 20.
What is the default value for the first index if you omit the first index value in a slice?
Answer:
The default value is zero (0).
Question 21.
What is the default value for the second index if you omit the second index value in a slice?
Answer:
The default value is the length of the string (the actual number of characters in the string).
Question 22.
What is the purpose of negative slice indices?
Answer:
Negative indices can be used to count from the right end of the string.
Question 23.
Name three types of sequence objects.
Answer:
The types of sequence objects are string, tuple and list.
Question 24.
Which item in the sequence is selected for an index value of -1?
Answer:
The last item in the sequence is selected for an index value of -1.
Question 25.
Just like C, C++, and Java, Python supports a character type, True or False?
Answer:
False. There is no character type in Python. Rather, a string’s items are characters.
Question 26.
How are lists formed?
Answer:
Lists are formed by placing a comma-separated sequence of expressions in square brackets.
Question 27.
What are the characteristics of list?
Answer:
A list is a sequence of items stored as a single object. Characteristics of list are:
(a) Items in a list can be accessed by indexing, and sublists can be accessed by slicing.
(b) Lists are mutable; individual items or entire slices can be replaced through assignment statements.
(c) Lists will grow and shrink as needed.
Question 28.
Write a program to create a list and print in sorted order.
Answer:
# Program to create a list and print in sorted order def getNumbers(): nums = [] # start with an empty list # sentinel loop to get numbers xStr = raw_input("Enter a number ( to quit) ››› ") while xStr != "": x = eval(xStr) nums.append(x) # add this value to the list xStr = raw_input("Enter a number ( to quit) ››› ") return nums data = getNumbers() data.sort() print "List in sorted order:" ,data ››› Enter a number ( to quit) ›› 7 Enter a number ( to quit) ›› 4 Enter a number ( to quit) ›› 8 Enter a number ( to quit) ›› 3 Enter a number ( to quit) ›› List in sorted order : [3, 4, 7, 8] ›››
Figure 6 Program for Q28
Question 29.
What are the capabilities of lists?
Answer:
Capabilities of lists are as follows:
(a) Append an item.
(b) Insert an item (at the beginning or into the middle of the list).
(c) Add a list of items to an existing list.
Question 30.
Find the output of the following programs
(a) ››› numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ››› numbers [0:1] (b) ››› x = [11, 22, 33] ››› x.reverse() ››› x (c) ››› x = [4, 6, 2, 1, 7, 9] ››› x.sort() ››› x (d) ››› = [[1, 2], 1, 1, [2, 1, [1, 2]]] ››› x.count(1) (e) # Add the squares given in the list squares = [1, 4, 9, 16] sum = 0 for num in squares: sum += num print sum (f) # Access every 3rd element in a list a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] i = 0 while i < len(a): print a[i] i = i + 3
Answer:
(a)[1]
(b)[33, 22,11]
(c)[1,2,4, 6, 7, 9]
(d)2
(e)30
(f)1 4 7 10
Multiple choice questions
Question 1.
List are similar to string in a way(s) like:
(a) Indexing
(b) Slicing
(c) Accessing individual elements
(d) All of the above
Answer:
(d)
Question 2.
An empty list is indicated by:
(a) {}
(b) []
(c) 0
(d) None of the above
Answer:
(b)
Question 3.
Which of the following statement is true?
(a) Lists is immutable
(b) Strings and tuples are mutable
(c) Lists are mutable
(d) None of these
Answer:
(c)
Question 4.
We can have list of following type:
(a) List of strings
(b) List of mixed value types
(c) List of numbers
(d) All of the above
Answer:
(d)
Question 5.
List containing another list is known as:
(a) Nested list
(b) Empty list
(c) Joint list
(d) None of these
Answer:
(a)