Python Fundamentals – List Manipulation

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 charac­ters, whereas lists can contain values of any type. Lists can contain values of mixed data types. A single list can con­tain numbers, strings, or other lists.
  • Unlike strings, which are immutable, it is possible to change individual ele­ments 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:

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.

You can also create lists of single characters or digits using keyboard input. For example,

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:

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:

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:

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.

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.

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.

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,

Note that while accessing individual elements, if you give index outside the legal indices Python will raise IndexError as shown below:

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:

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:

Let’s say you want to access the last three elements of numbers.

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:

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:

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:

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:

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

Figure 16.1 List traverse using while loop

Example 2

Figure 16.2 Traversing list using for loop

Example 3

Figure 16.3 Traversing list using while loop and len function

Example 4

Figure 16.4 Traversing list and printing even numbers

Program to print elements of a list with their positive and negative indexes

Example 5

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:

The + operator when used with lists requires both the operands to be of list types other wise it will produce error. For example,

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.

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.

A slice operator on the left side of an assignment can update multiple elements:

Comparing Lists
Tests whether the contents of two or more lists are the same. The comparison operators can be used to compare lists.

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.

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:

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:

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:

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:

len()
The built-in len() function is used to get the length of list.

It is possible to nest lists (create lists containing other lists), for example:

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:

count()
To find out the number of times a value occurs in a list, use the count(value) method.

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’.

insert()
To insert an item into a list, use insert() method. This example inserts an item at the beginning of a list:

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.

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.

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.

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:

The confusion usually occurs when users want a sorted copy of a list while leaving the original alone.

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[:] is a slice containing all the elements of x, effectively a copy of the entire list.

Example 6

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[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[:i] is the sublist starting with index 0 in A and continuing up to and including the element with index i-1:

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:

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:

extend() method takes a list as an argument and appends all of the elements:

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:

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:

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:

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:

Figure 1 Program for Q16

Question 17.
Write a program to print domain name using slice operation.

Answer:

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:

Figure 3 Program for Q18

Question 19.
Write a program to print average of entered number using two different methods.

Answer:

Figure 4 Program for Q19

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:

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

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)

About the author

James Palmer

Leave a Comment