LISTS - Python
LISTS - Python
➢ A list begins with an opening square bracket and ends with a closing square bracket,
[]. ➢ Values inside the list are also called items and are separated with commas.
value is at index 2, and so on. ➢ For example, type the following expressions into the
interactive shell.
➢ The expression 'Hello ' + spam[0] evaluates to 'Hello ' + 'cat' because spam[0]
evaluates to the string 'cat'. This expression in turn evaluates to the string value 'Hello
cat'.
➢ If we use an index that exceeds the number of values in the list value then, python
gives IndexError.
➢ Indexes can be only integer values, not floats. The following example will cause a
TypeError error:
➢ Lists can also contain other list values. The values in these lists of lists can be
accessed using multiple indexes.
➢ The first index dictates which list value to use, and the second indicates the value
within the list value. Ex, spam[0][1] prints 'bat', the second value in the first list.
Negative Indexes
➢ We can also use negative integers for the index. The integer value -1 refers to the last index
in a list, the value -2 refers to the second-to-last index in a list, and so on.
➢ ➢ As a shortcut, we can leave out one or both of the indexes on either side of the
colon in the slice.
o Leaving out the first index is the same as using 0, or the beginning of the list.
o Leaving out the second index is the same as using the length of the list, which will
slice to the end of the list.
➢ We can also use an index of a list to change the value at that index.
➢ Ex: spam[1] = 'aardvark' means “Assign the value at index 1 in the list spam to the
string 'aardvark'.”
combines two strings into a new string value. ➢ The * operator can also be used with
➢ Which is bad way to write code because it leads to have a duplicate code in the
program.
➢ Instead of using multiple, repetitive variables, we can use a single variable that
contains a list value.
➢ For Ex: The following program uses a single list and it can store any number of cats
that the user types in.
➢ Program:
Output:
➢ A for loop repeats the code block once for each value in a list or list-like value.
Program
Output:
➢ A common Python technique is to use range (len(someList)) with a for loop to iterate
over the indexes of a list.
➢ The code in the loop will access the index (as the variable i), the value at that index
(as supplies[i]) and range(len(supplies)) will iterate through all the indexes of
➢ We can determine whether a value is or isn’t in a list with the in and not in operators.
➢ in and not in are used in expressions and connect two values: a value to look for in a
list and the list where it may be found and these expressions will evaluate to a
Boolean value.
➢ The following program lets the user type in a pet name and then checks to see whether
the name is in a list of pets.
Program
Output
➢ When assigning a value to a variable, we will frequently use the variable itself
➢ Instead of left-side program we could use right-side program i.e., with the augmented
assignment operator += to do the same thing as a shortcut.
➢ The Augmented Assignment Operators are listed in the below table:
➢ The += operator can also do string and list concatenation, and the *= operator can do
string and list replication.
1.4 Methods
➢ A method is same as a function, except it is “called on” a value.
➢ The method part comes after the value, separated by a period.
➢ Each data type has its own set of methods.
➢ The list data type has several useful methods for finding, adding, removing, and
manipulating values in a list.
➢ When there are duplicates of the value in the list, the index of its first appearance is
returned.
➢ To add new values to a list, use the append() and insert() methods. ➢ The append()
method call adds the argument to the end of the list.
➢ The insert() method can insert a value at any index in the list. The first argument to
insert() is the index for the new value, and the second argument is the new value to be
inserted.
➢ The remove() method is passed the value to be removed from the list it is called on.
➢ Attempting to delete a value that does not exist in the list will result in a ValueError
error.
➢ If the value appears multiple times in the list, only the first instance of the value will
be removed.
➢ The del statement is good to use when you know the index of the value you want to
remove from the list. The remove() method is good when you know the value you
want to remove from the list.
Sorting the Values in a List with the sort() Method
➢ Lists of number values or lists of strings can be sorted with the sort() method.
➢ You can also pass True for the reverse keyword argument to have sort() sort the values
in reverse order.
➢ There are three things you should note about the sort() method.
o First, the sort() method sorts the list in place; don’t try to return value by
writing code like spam = spam.sort().
o Second, we cannot sort lists that have both number values and string values in
them.
➢ If we need to sort the values in regular alphabetical order, pass str.lower for the key
keyword argument in the sort() method call.
1.5 Example Program: Magic 8 Ball with a List
➢ We can write a much more elegant version of the Magic 8 Ball program. Instead of
several lines of nearly identical elif statements, we can create a single list.
➢ The expression you use as the index into messages: random .randint (0, len(messages)
- 1). This produces a random number to use for the index, regardless of the size of
messages. That is, you’ll get a random number between 0 and the value of
len(messages) - 1.
Exceptions to Indentation Rules in Python
➢ The amount of indentation for a line of code tells Python what block it is in.
➢ lists can actually span several lines in the source code file. The indentation of these
lines do not matter; Python knows that until it sees the ending square bracket, the list
is not finished.
➢ We can also split up a single instruction across multiple lines using the \ line
continuation character at the end.
➢ We used [0:7] and [8:12] to refer to the characters that we don’t wish to replace.
Notice that the original 'Zophie a cat' string is not modified because strings are
immutable.
List
➢ A list value is a mutable data type: It can have values added, removed, or changed.
➢ The list value in eggs isn’t being changed here; rather, an entirely new and different list
value ([4, 5, 6]) is overwriting the old list value ([1, 2, 3]).
Figure: When eggs = [4, 5, 6] is executed, the contents of eggs are replaced with a
new list value.
➢ If we want to modify the original list in eggs to contain [4, 5, 6], you would have to
delete the items in that and then add items to it.
Figure: The del statement and the append() method modify the same list value in place .
The Tuple Data Type
➢ The tuple data type is almost identical to the list data type, except in two ways. ➢
First, tuples are typed with parentheses, ( and ), instead of square brackets, [ and ].
➢ Second, benefit of using tuples instead of lists is that, because they are immutable and
their contents don’t change. Tuples cannot have their values modified, appended, or
removed.
➢ If you have only one value in your tuple, you can indicate this by placing a trailing
comma after the value inside the parentheses.
➢ The functions list() and tuple() will return list and tuple versions of the values passed to
them.
References
➢ As , variables store strings and integer values.
➢ We assign 42 to the spam variable, and then we copy the value in spam and assign it to
the variable cheese. When we later change the value in spam to 100, this doesn’t affect
the value in cheese. This is because spam and cheese are different variables that store
different values.
➢ But lists works differently. When we assign a list to a variable, we are actually
assigning a list reference to the variable. A reference is a value that points to some bit
of data, and a list reference is a value that points to a list.
➢ When we create the list ❶, we assign a reference to it in the spam variable. But the
next line copies only the list reference in spam to cheese, not the list value itself. This
means the values stored in spam and cheese now both refer to the same list.
➢ There is only one underlying list because the list itself was never actually copied. So
when we modify the first element of cheese, we are modifying the same list that spam
refers to.
➢ List variables don’t actually contain lists—they contain references to lists.
Figure: spam = [0, 1, 2, 3, 4, 5] stores a reference to a list, not the actual list.
➢ The reference in spam is copied to cheese. Only a new reference was created and
stored in cheese, not a new list.
Figure: spam = cheese copies the reference, not the list
➢ When we alter the list that cheese refers to, the list that spam refers to is also
changed, because both cheese and spam refer to the same list.
Figure: cheese[1] = 'Hello!' modifies the list that both variables refer to
➢ Variables will contain references to list values rather than list values themselves.
➢ But for strings and integer values, variables will contain the string or integer value.
➢ Python uses references whenever variables must store values of mutable data types,
such as lists or dictionaries. For values of immutable data types such as strings,
integers, or tuples, Python variables will store the value itself. Passing
References
➢ References are particularly important for understanding how arguments get passed to
functions.
➢ When a function is called, the values of the arguments are copied to the parameter
variables.
Program Output
➢ when eggs() is called, a return value is not used to assign a new value to spam.
➢ Even though spam and someParameter contain separate references, they both refer to
the same list. This is why the append('Hello') method call inside the function affects
the list even after the function call has returned
Figure: cheese = copy.copy(spam) creates a second list that can be modified independently of
the first.
>>> import copy
>>> spam = ['A', 'B', 'C', 'D']
>>> cheese = copy.copy(spam)
>>> cheese[1] = 42
>>> spam
Output: ['A', 'B', 'C', 'D']
>>> cheese
Output: ['A', 42, 'C', 'D']
copy function
>>> import copy
>>> old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
>>> new_list = copy.copy(old_list)
>>> old_list[1][0] = 'BB'
>>> print("Old list:", old_list)
>>> print("New list:", new_list)
>>> print(id(old_list))
>>> print(id(new_list))
Output:
Old list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
New list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
1498111334272
1498110961152
deepcopy() Function
>>> import copy
>>> old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
>>> new_list = copy.deepcopy(old_list)
>>> old_list[1][0] = 'BB'
>>> print("Old list:", old_list)
>>> print("New list:", new_list)
>>> print(id(old_list))
>>> print(id(new_list))
Output
Old list: [[1, 1, 1], ['BB', 2, 2], [3, 3, 3]]
New list: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
1498111298880
1498111336064