WHAT WE ARE GOING TO LEARN, LET'S KEEP AN EYE :
A) Creating lists
B) Creating lists from existing sequence
C) Accessing lists
=> Accessing individual elements
=> Difference from strings
=> Traversing a list
=> How it works
D) Comparing lists
L3 List Operators :
A) Joining lists
B) Repeating or Replicating lists
C) Slicing the lists
=> Using slices for list modification
L4 Making True Copy Of A List
L5 List Functions And Methods :
1. the len() function
2. the list() method
3. the index() method
4. the append() method
5. the extend() method
6. the insert() method
7. the pop() method
8. the remove() method
9. the clear() method
10. the count() method
11. the reverse() method
12. the sort() method
13. the sorted() method
14. the min(), max(), sum() method
L6 Nested Lists :
A) Two-Dimensional lists
=> Creating a 2D list
=> Traversing a 2D list
=> Accessing/Changing individual elements in a 2D list
L7 Working With Lists(List Manipulation) :
A) Appending a single element to a list
B) Appending a list of elements to a list
C) Inserting an element in a list
D) Modifying/Updating elements i a list
E) Deleting element from a list
=> Deleting an element using its index
=> Deleting an element using its value
=> Deleting a sub list from a list
F) Sorting a list
L1 INTRODUCTION :
What is list in python ?
The python lists are containers that are used to store a list of values of any type. Unlike other variables python list are mutable i.e., you can change the elements of a list in place; python will not create a fresh list when you make changes to an element of a list. List is a type of sequence like strings and tuples but it differs from them in the way that lists are mutable but strings and tuples are immutable.
We shall be talking about creating and accessing
list, various list operations and list manipulation through some built-in
functions.
L2 CREATING AND ACCESSING LISTS :
A list is a standard data type in python that
can store a sequence of values belonging to any type. The lists are depicted
through square brackets [ ] for example, following are some lists in
python:
[ ] #empty list
[1,2,3] #list of integers
[1,2.5,9.8,9] #list of numbers
['a', 'b', 'f', 'g', 'k', 'y'] #list of characters
['a', 9, 'b', 8, 'd', 5, 'm' ,7, 'n'] #list of
mixed elements
['Arjun', 'Bhima', 'Pandav', 'Mahabharat']
#list of strings
A) CREATING LISTS :
To create a list put a number of expressions in
square brackets. That is, use square brackets to indicate the start and the end
of the list, and separate the items by commas.
Thus, to create a list you can write in the form
given below :
>>> L = []
>>> L = [values, ...]
The empty list
The empty list is [ ]. It is equivalent to 0 or ' ' and like them it also has truth value as false. You can also create an empty list as l = list( ) it will generate an empty list and name it as l. The brackets only appear in the beginning and at the end of the list.
Nested lists
A list may have an element in it, which itself
is a list. Such a list is called nested list example-
L = [12, 45, [54, 89, 75], 456, 45, 63]
L is a nested list with 6 elements and L[2]
element is a list [54,89,75]. Length of L is 6 as it counts [54,89,75] as one
element. Also, as L[2] is a list [54,89,75], which means L[2][0] will give 54
and L[2][1] will give 89.
B) CREATING LISTS FROM EXISTING SEQUENCE :
You can also use the built-in list type object
to create a list from sequences as per the given syntax given below -
L = list(<sequence>)
Where sequence can be any kind of sequence
object including strings, tuples, and lists. Python creates the individual
elements of a list from the individual elements of a passed sequence. For
example-
>>> L1 = list('world')
>>> L1
['w', 'o', 'r' ,'l', 'd']
>>> t = (1,2,3)
>>> L2 = list(t)
>>> L2
[1, 2, 3]
You can use this method of creating list of
single character or single digits via keyboard input-
>>> L1 = list(input(“Enter the elements of the list : ”))
Enter the elements of the list : 123456
>>> L1
[1,2,3,4,5,6]
Most commonly used method to input list is eval(input()) as given
below -
>>> List = eval(input("Enter list to be added : "))
>>> Print("list you entered : ", List)
When you will execute this, it will work
somewhat like -
Enter list to be added : [1,2,3,4,5]
List you entered : [1,2,3,4,5]
Note : sometimes eval() does not work in python
shell, then you can try it on python script.
C) ACCESSING LISTS :
Lists are mutable sequences having progression of elements. There must be a way to access its individual elements and certainly there is. But before we start accessing individual elements, let us discuss the similarity of lists with strings that will make it very clear to you how individual elements are accessed in lists - the way you access the string elements.
List are sequences just like strings do. They also index their individual elements, just like strings do. Look at the figure given below, that talks about indexing of strings. In the same manner, list elements are also indexed, i.e., forward indexing as 0, 1, 2 , 3,... And backward indexing as -1, -2, -3, -4,...
List are similar to strings in the following way
:
Length - function len( ) returns the number of items(count) in the list L
Indexing and slicing - L[i] returns the item at index i(the first
item has index 0), and L[I : j] returns a new list, containing the
objects at indexes between i and j (excluding index j).
Membership operators - both 'in' and 'not in' operators work on lists
just like they work on other sequences. That is, in tells if an element is
present in the list or not, and not in does the opposite.
Concatenation and replication operators + and * - the + operator adds one list to the end of
another list. The * operator repeats a list.
- Accessing Individual Elements -
As mentioned, the individual elements of a list
are accessed through their indexes. For example -
>>> vowels = ['a','e','i','o','u']
>>> vowels[0]
'a'
>>> vowels[-2]
'o'
>>> vowels[-5]
'a'
Just like strings if you give index outside the
legal indices (0 to length -1 or -length, -length+1, ..., until -1) while
accessing individual elements, python will raise index errors
- Difference from strings -
Although lists are similar to strings in many
ways, yet there is an important difference in mutability of the two. Strings are
not mutable, while lists are. You cannot change individual elements of a string
in place, but lists allow you to do so. That is, following statement is fully
valid for lists but not for strings -
L[i] = <elements>
For example, if you want to change some of these
vowels, you may write something as shown below -
>>> vowels[0] = 'A'
>>> vowels
['A', 'e', 'i', 'o', 'u']
- Traversing a list -
Recall that traversal of a sequence means
accessing and processing each element of it. Thus, traversing a list also means
the same and same is the tool for it, i.e., the python loops. That is way
sometimes we call traversing as looping over a sequence.
The
for loop makes it easy to traverse or loop over the items in a list, as per
following syntax -
for<item>in<List>:
process each item here
For example, following loop shows each item of a
list L in separate lines -
>>> L = ['p', 'y', 't', 'h', 'o', 'n']
>>> for a in L:
print(a)
The above loop will produce result as :
p
y
t
h
o
n
- How It Works -
The loop variable a in above loop will be
assigned the list elements, on at a time. So, loop-variable a will be assigned
'p' in first iteration and hence 'p' will be printed; in second iteration , a
will get 'y' and 'y' will be printed; and so on.
If you only need to use the indexes of elements
to access them, you can use functions range() and len() as per following
syntax:
for index in range(len(L)) :
process List[index] here
D) COMPARING LISTS :
You can compare two lists using standard comparison operators of python, i.e., <, >, ==, !=, etc. Python internally compares individual elements of lists(and tuples) in lexicographical order. This means that to compare equal, each corresponding element must compare equal and the two sequences must be of the same type i.e., having comparable types of values. Consider following examples -
>>> L1, L2 = [1,2,3], [4,5,6]
>>> L3 = [1, [2, 3]]
>>> L1 == L2
True
>>> L1 == L3
False
For comparison operators, the corresponding
elements of the two list must be of comparable types, otherwise python will
give error.
Python raised error above because the
corresponding second elements of list L1[1] and L3[1] are not of comparable
types. L1[1] is integer(2) and l3[1] is a list[2, 3] and list and numbers are
not comparable types in python.
Python gives the final result of non-equality
comparison as soon as it gets a result in terms of true/false from
corresponding elements comparison. If corresponding elements are equal, it goes
on to the next element, and so on, until it finds elements that differ.
Subsequent elements are not considered (even if they are really big).
L3 LIST
OPERATORS :
The most common operations that you perform with
lists include joining lists, replicating lists and slicing lists. In this
section, we are going to talk about the same.
A) JOINING LISTS :
Joining two lists is very easy just like
you perform addition, literally :-) . The concatenation operator + , when used
with two lists, joins two lists. Consider the example given below -
>>> list1 = [1, 2, 3]
>>> list2 = [6, 7, 8]
>>> list1 + list2
[1, 2, 3, 6, 7, 8]
As you can see that the resultant list has
firstly elements of first list list1 and followed by elements of second list
list2.
The + operator when used with lists
requires that both the operands must be of list type. You cannot add a number
or any other value to a list. For example
>>> list1 = [10, 20, 30]
>>> list1 + 2
Traceback (most recent call last):
File “<pyshell#13>”, line 1, in <module>
list1 +=
2
TypeError: can only concatenate list(not”int”)to
list
>>> list1 + "abc"
Traceback (most recent call last):
File “<pyshell#13>”, line 1, in <module>
list1 +=
2
TypeError: can only concatenate list(not”int”)to
list
Fair enough, so now you know that you cannot add
any number or a string to a list using the '+' operator as obvious through
above given reference expression 1&2. But what will happen if you write
expression list1 += 2 and list1 += "abc" ?
>>> list1 = [10, 20, 30]
>>> list1 += 2
Traceback (most recent call last):
File “<pyshell#13>”, line 1, in <module>
list1 +=
2
>>> list1 += "abc"
>>>
Surprised? Just moments back list1 +
"abc" gave error and now list1 += "abc" gives no error.
Well, don't be surprised, just read on.
as you know that for any operator to work, there are rules for its operand types, e.g., + cannot add operands of list and int types. And as mentioned in chapter 8 that += is different from + for mutable iterable types such as lists; it has different rules for lists.
When += is used with lists then it requires the
operand on the right to be an iterable and it will add each element of the
iterable to the list. Now if you check the contents of list1 after the above
given expression, it will show something like.
=> list1 += "abc"
=> list1
[10, 20, 30, 'a', 'b', 'c']
=>
For the same reason list1 += [2] will work but
list1 += 2 will not, because [2] is a list(an iterable) and 2 is an integer.
B)
REPEATING
OR REPLICATING LISTS -
Like strings, you can use * operator to
replicate a list specified number of times, e.g., (considering the same list
list1 = [1, 2, 3, 4] )
>>> list1*2
[1, 2, 3, 4, 1, 2, 3, 4]
Like strings, you can only use an integer with a
* operator when trying to replicate a list.
C)
SLICING
THE LISTS -
List slices, like strings slices are the sub
part of a list extracted out. You can use indexes of list elements to create
list slices as per following format :
Sequence= l[start:stop]
The above statement will create a list slice
namely sequence having elements of list l on indexes start, start+1, start+2, ...,
stop-1. Recall that index on last limit is not included in the list slice. The
list slice is a list in itself, that is, you can perform all operations on it
just like you perform o lists.
Consider the following example -
>>> list = [10, 20, 30, 40, 50, 60, 70, 80,
90]
>>> seq = list[3:-3]
>>> seq
[40, 50 ,60]
>>> seq[1] = 100
>>> seq
[40, 100, 60]
For normal indexing, if the resulting index is
outside the list, python raises an IndexError exception. Slices are treated as
boundaries instead, and the result will simply contain all items between the
boundaries. For the start and stop given beyond list limits in a list slice
(i.e., out of bounds), python simply returns the elements that fall between
specified boundaries, if any, without raising any error.
For example, consider the following -
>>> list = [10, 20, 30, 40, 50, 60, 70, 80,
90]
>>> list[3:30]
[40, 50, 60, 70, 80, 90]
>>> list[-15:7]
[10, 20, 30, 40, 50, 60, 70]
>>> L1[1, 2, 3, 4, 5, 6, 7]
>>> L1[2:5]
[3, 4, 5]
>>> L1[6:10]
[7]
>>> L1[10:20]
[]
Lists also support slice steps. That is, if you
want to extract, not consecutive but every other element of the list, there is
a way out - the slice steps. The slice steps are used as per following format :
Seq = l[start:stop:step]
Consider some examples to understand this.
>>> list
[10, 20, 30, 40, 50, 60, 70, 80, 90]
>>> list[0:10:2]
[10, 30, 50, 70, 90]
>>> list[2:10:3]
[30, 60, 90]
>>> list[::3]
[10, 40, 70]
Consider some more examples :
Seq = L[::2] # get every other item, starting
with first element
Seq = L[5::2] # get every other item, starting
with sixth element(index 5)
Like strings, if you give <listname> [::
-1], it will reverse the list e.g., for a list say list = [1,2,3,4,5],
following expression will reverse it -
>>> list[::-1
[5,4,3,2,1]
- Using Slices For List Modification
You can use slices to overwrite one or more list
elements with one or more other elements, following examples will make it clear
to you -
>>> L = ["one", "two",
"three"]
>>> L[0:2] = [0, 1]
>>> L
[0, 1, "three"]
>>> L = ["one", "two",
"three"]
>>> L[0:2] = "a"
>>> L
["a", "three"]
In all the above examples, we have assigned new
values in the form of a sequence. The values being assigned must be a sequence,
i.e., a list or string or tuple etc. For example, following assignment is also
valid.
>>> L1 = [1,2,3]
>>> L1[2:] = "420"
>>> L1
[1,2,'4','2','0']
But if you try to assign a non-sequence value to
a list slice such as a number, python will give an error, i.e.,
>>> L1[2:] = 420
Type error : can only assign an iterable
But here, you should also know something, if you
give a list slice with range much outside the length of the list, it will
simply add the values at the end i.e.
>>> L1 = [1,2,3]
>>> L1[10:20] = "abcd"
>>> L1
[1,2,3,'a','b','c','d']
L4 MAKING
TRUE COPY OF A LIST :
Sometimes you need to make a copy of a list and
you generally tend to do it using assignment, e.g.,
>>> a = [1,2,3]
>>> b = a
But it will not make b as a duplicate list of a
; rather just like python does, it will make label b to point to where label a
is pointing to, i.e., as shown in adjacent figure.
It will work fine as long as we do not modify
lists. Now, if you make changes in any of the lists, it will be reflected in
other because a and b are like aliases for the same list. See below-
>>> a = [1,2,3]
>>> b = a
>>> a[1] = 5
>>> a
[1,5,3]
>>> b
[1,5,3]
See, along with list a, list b gets modifies.
What if you want that the copy list b should remain unchanged while we make
changes in list a ? That is, you want both lists to be independent of each
other as shown in the adjacent figure. For this, you should create copy of the
list as follows -
>>> a = list(a)
Now a and b are separate lists. See below-
>>> a = [1,2,3]
>>> b = list(a)
>>> a[1] = 5
>>> a
[1,5,3]
>>> b
[1,2,3]
Thus, true independent copy of a list is made
via list() method; assigning a list to another identifier just creates an alias
for the same list.
There is another way of doing it, i.e., creating
the true copy of a list, by using the copy() method. You can use the copy()
method as per this syntax -
L.copy()
Where L is the list, whose copy is to be made.
For example,
>>> La = [11,12,13]
>>> Lb = la.copy()
>>> La
[11,12,13]
>>> Lb
[11,12,13]
>>> Lb[0] += 10
>>> Lb
[21,12,13]
>>> La
[11,12,13]
The same thing that you did by using list() and
copy() functions, can also be achieved as -
Listcopy = List[ :]
So, in nutshell, you can create a true copy of a
list by using any one of the following three ways :
(i) by using the list() method
(ii) by storing all elements of the list
using list slice in its copy
(iii) by using the copy() method.
L5 LIST
FUNCTIONS AND METHODS :
Python also offers many built-in functions and
methods of manipulation, you will learn about many other built-in
powerful list methods of python used for list manipulation.
Every list object that you create in python is
actually an instance of list class(you need not do anything specific for this;
python does it for you - you know built-in). The list manipulation methods that
are being discussed below can be applied to lists as per following syntax -
<listobject>.<method name>()
In the following examples, we are referring to
<listobject> as list only i.e., you have to replace list with a legal
list(i.e., either a list literal or a list object that holds a list).
Let us now have a look at some useful built-in
list manipulation methods.
1. The len() function
Returns the length of its argument list, i.e.,
it returns the number of elements in the passed list. The len() function is a
python standard library function. It works as per following syntax -
Len(<list>)
Examples -
>>> len([1,2,3])
3
>>> list1 = [4,2, [9,1], (4,5)]
>>> len(list1)
4
2. The list() method
Returns a list created from the passed argument,
which should be a sequence type(string, list, tuple etc.). If no argument is
passed, it will create an empty list. It works as per the following syntax
-
List([<sequence>])
Examples -
>>> list("hello")
['h', 'e', 'l', 'l', 'o']
>>> a = list((55,66,77))
A
[55,66,77]
>>> b = list()
>>> b
[]
>>>> c = list({'a':101, 'b':201})
>>> c
['a', 'b']
3. The index() method
This function returns the index of first matched item from the list. It is used as per following format -
List.index(<item>)
For example, for a list
>>> L1 = [11, 12, 13, 14, 15, 16, 17]
>>> L1.index(12)
1
However, if the given item is not in the list,
it rises ValueError exception (see below)
List.index(99)
ValueError : 99 is not in list
4. The append() method
The append() method adds an item to the end of
the list. It works as per the following syntax -
List.append(<item>)
For example, to add a new item 88 to a list
containing various numbers, you may write -
>>> num = [11, 22, 55, 66, 99]
>>> num.append(88)
>>> num
[11, 22, 55, 66, 99, 88]
The append() does not return the new list, just
modifies the original list. To understand this, consider the following example
-
>>> list = [1, 2, 3]
>>> list2 = list.append(50)
>>> list2
>>> list
[1, 2, 3, 50]
5. The extend() method
The extend method is also used for adding
multiple elements(given in the form of a list) to a list. But it is different
from append(). First, let us understand the working of extend( ) function then
we'll talk about the difference between these two functions.
The extend() function works as per the following
format -
List.extend(<list>)
That is extend() takes a list as an argument and
appends all of the elements of the argument list to the list object on which
extend() is applied.
Consider the following example -
>>> list = [1, 2, 3, 4, 5]
>>> list2 = [6, 7]
>>> list.extend(list2)
>>> list
[1, 2, 3, 4, 5, 6, 7]
>>> list2
[6, 7]
The above example left list2 unmodified. Like
append(), extend() also does not return any value. Consider the following
example -
>>> list3 = list.extend(list2)
>>> list3
[]
- Difference Between Append() And Extend() :
While append() function adds one element to a
list, extend() can add multiple elements from a list supplied to it as
argument. Consider the following example that will make it clear to you -
>>> list = [1, 3, 5]
>>> list2 = [6, 7]
>>> list.append(8)
>>> list
[1,3,5,8]
>>>list.append(12, 14)
Tracback(most recent call last):
List.append(12, 14)
TypeError : append() takes exactly one
argument(2 given)
>>> list.append([12, 14])
>>> list
[1, 3, 5, 8, [12, 14]]
>>> len(list)
5
>>> list2.extend([12, 14])
>>> list2
[6, 7, 12, 14]
>>> list3 = [10, 20]
>>> list2.extend(list3)
>>> list2
[6, 7, 12, 14, 10, 20]
>>> len(list2)
6
6. The Insert() method
The insert( ) method is also an insertion method
for lists, like append and extend methods. However, both append() and extend()
insert the element(s) at the end of the list. If you want to insert an element
somewhere in between or any position of your choice, both append() and extend()
are of no us. For such a requirement insert() is used. The insert() function
inserts an item at a given position.
It is used as per the following syntax -
List.insert(<ind>, <item>)
The first argument <ind> is the index of
the element before which the second argument <item> is to be added.
Consider the following example -
>>> list = ['a', 'b', 'c']
>>> list.insert(2,'d')
>>> list
['a', 'b', 'd', 'c']
For the function insert, we can say that -
List.insert(0, x)
Will insert element x at the end of the list
i.e., at index 0 (zero)
List.insert(len(a), x)
Will insert element x at the end of the list -
index equal to length of the list ; thus, it is equivalent to list.append(x).
If index is greater than len(list), the object is simply appended. If, however,
index is less than zero and not equal to any of the valid negative index
of the list(depends on the size of the list), the object is prepended,
i.e., added in the beginning of list e.g., for a list list1 = ['a', 'e', 'i',
'o', 'u'], if we do -
# valid negative indexes are -1, -2, -3, -4
>>> list1.insert(-9, 'k')
>>> list1
# list prepended with element 'k'
['k', 'a', 'e', 'i', 'o', 'u']
7. The pop() method
The pop() method is used to remove the item from
the list. It is used as per following syntax -
List.pop(<index>)
Thus, pop() removes an element from the given
position in the list, and return it. If no index is specified, pop() removes
and returns the last item in the list. Consider some examples -
>>> list1
[1, 2, 3, 5, 4, 5, 6]
>>> element = list1.pop(3)
>>> element
5
>>> list1
[1, 2, 3, 4, 5, 6]
>>> element2 = list1.pop()
>>> element2
6
>>> list1
[1, 2, 3, 4, 5]
The pop() method raises an exception if the list
is already empty. Consider this example -
>>> list2 = []
>>> list2.pop()
Traceback(most recent calls last):
List2.pop()
Index Error : pop from empty list
8. The remove() method
While pop() removes an element whose positions
is given, what if you know the value of the element to be removed, but you do
not know its index or positions in the list ? Well, python thought it in
advance and made available the remove() method. The remove() method removes the
first occurrence of the given item from the list. It is used as per following
format :
List.remove(<value>)
The remove() will report an error if there is no
such item in the list. Consider this example -
>>> list1 = [1, 2, 3, 6, 4, 5, 6, 7]
>>> list1.remove(5)
>>> list1
[1, 2, 3, 6, 4, 6, 7]
>>> list1.remove(6)
>>> list1
[1, 2, 3, 4, 6, 7]
>>> list1.remove(10)
Traceback(most recent calls last):
List1.remove(10)
ValueError : list1.remove(x) : x not in list
9. The clear() method
This method removes all the items from the list
and the list becomes empty list after this function. This function returns
nothing, it is used as per following format.
List.clear()
For instance, if you have a list list1 as
>>> list1 = [1, 2, 3, 4, 5]
>>> list1.clear()
>>> list1
[]
Unlike del <listname> statement, clear()
removes only the elements and not the list element. After clear(), the list
object still exists as an empty list.
10. The count() method
This function returns the count of the item that
you passed as argument. If the given item is not in the list, it returns zero.
It is used as per following format -
List.count(<item>)
For instance, for a list list1 =
[10,20,30,40,20,50,20,10,40]
>>> list1.count(20)
3
>>> list1.count(80)
0
11. The reverse() method
The reverse() reverses the items of the list.
This is done "in place", i.e., it does not create a new list. The
syntax to use reverse method is -
List.reverse()
>>> L1 = [1, 2, 3, 4, 5, 6]
>>> L1.reverse()
>>> L1
[6, 5, 4, 3, 2, 1]
>>> L2 = [7, 8, 9]
>>> L3 = l2.reverse()
>>> L3
>>> L2
[9, 8, 7]
12. The sort() method
The sort() function sorts the items of the list,
by default increasing order. This is done "in place", i.e., it does
not create a new list. It is used as per following syntax -
List.sort([<reverse = false/true>])
>>> L1 = [8, 6, 1, 5, 7, 4, 2, 3, 9]
>>> L1.sort()
>>> L1
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Like reverse(), sort() also performs its
function and does not return anything. To sort a list in decreasing order using
sort(), you can write -
>>> L1.sort(reverse = true)
13. The sorted() function
This function takes the name of the list as an
argument and returns a new sorted list with sorted elements in it. It works as
per the following syntax -
Sorted(<iterable_sequence>,[reverse =
false])
For example, for a list val = [20, 80, 30, 10,
50], sorted() will work as -
>>> sval = sorted(val)
>>> sval
[10, 20, 30, 50, 80]
>>> rsval = sorted(val, reverse = true)
>>> rsval
[80, 50, 30, 20, 10]
14. The min(), max(), sum() functions
The min(), max(), sum() functions take the list
sequence and return the minimum element, maximum element and sum of the
elements of the list respectively. These functions work as per the following
syntax -
Min(<list>)
Max(<list>)
Sum(<list>)
Where the <list> is a list of elements on
which these functions will work. For example, consider the list val = [10, 20,
30, 40 ,50]
>>> min(val)
10
>>> max(val)
50
>>> sum(val)
150
L6 NESTED
LISTS :
You know that lists are the objects that can
hold objects of any other types as its elements. Since lists are objects
themselves, they can also hold other list(s) as its element(s). Carefully go
through the adjacent code shown that creates four lists namelyLl1, L2, L3, L4.
>>> L1 = [22, 11]
>>> L2 = [33, 11]
>>> L3 = [11, 44, L2]
>>> L4 = [11, L1, L3, 15]
Out of the 4-list created above, two are nested
lists, i.e., L3 and L4 are nested lists as they contain one or more lists as
their elements. So, when you display or print the contents of lists L3 and L4,
it will be like
>>> L3
[11, 44, 33, 11] # {the 3rd element of L3, i.e., L3[2] is the
list L2, i.e., [33, 11]}
>>>L4
[11, [22, 11], [11, 44, [33, 11]], 15]
{the 3rd element of L4, i.e., L4[2] is the l1,
i.e., [22,11]. The 4th element of L4, i.e., L4[3] is the list L3, which is a
nested list itself.}
So, you can say that a list that has one or more
lists as its elements is a nested list. A two dimensional list is also a
nested list. Let us see how.
A) TWO DIMENSIONAL LISTS :
A two-dimensional list is a list having all its
elements as lists of same shape, i.e., all are singular lists(i.e., non-nested)
with a length of 2 elements. Following representation will make it clear.
L1 = [[1, 2], [9, 8], [3, 4]]
Regular two-dimensional lists are the nested
lists with these properties :
(i) all elements of a 2d list have
same shape
(ii) the length of 2d list talk about
number of rows in it.
(iii) the length of a single row gives number of
columns in it.
Ragged list - a list that has lists with
different shapes as its elements is also a 2d list but it is an irregular 2d
list, also known as ragged list. For example -
L2 = [ [1, 2, 3], [4, 5] ]
As its one element has a length as 3 while its 2
element is a list with a length of 2 elements.
Now, let us quickly learn how you can use a
two-dimensional list.
- Creating A 2D List :
To create a 2D list by inputting element by
element, you can employ a nested loop as shown in the program below : one loop
for rows and the other loop for reading individual elements of each row.
L = []
R = int(input("how many rows ? "))
C = int(input("how many columns ? "))
For i in range :
row = []
for j in range(c) :
element =
int(input("element"+str(i)+","+str(j)+":"))
row.append(element)
list.append(row)
Print("list created is :", l)
- Traversing A 2D List :
To traverse a 2D list element by element, you
can employ a nested loop as earlier : one loop for rows and another for
traversing individual elements of each row.
L = []
R = int(input("how many rows ? "))
C = int(input("how many columns ? "))
For i in range :
row = []
for j in range(c) :
element =
int(input("element"+str(i)+","+str(j)+":"))
row.append(element)
list.append(row)
Print("list created is :")
Print("l = [")
For i in range(r) :
print("\t", end =
"")
for j in range(c) :
print(l[i][j], end =
"")
print("]")
Print("\t]")
- Accessing/Changing Individual Elements In A 2D List :
You can access individual elements in a 2d list
by specifying its indexes in square brackets, e.g., to access 3rd row's 3rd element
from 2d list namely l that we created in previous sections, you will write-
L[2][2]
Indexes begin with 0 and go till n-1
Using the same syntax, you can also change a
specific value in a 2d list as lists are mutable types, i.e., following statement
will change the 3rd element of 2nd row to 420 -
L[1][2] = 420
L7 WORKING WITH LISTS(LIST MANIPULATION) :
Now that you learnt to access the individual
elements of a list, let us talk about how you can perform various operations on
lists like - appending, inserting, updating, deleting, sorting, etc.
A) APPENDING A SINGLE ELEMENT TO A LIST -
To append a single element to a list, you can
use the append() method of lists. The append() method adds a single item to the
end of the list. It can be done as per the following format -
L.append(item)
Where L is the list to which the element is
being appended. For example -
>>> L = [10, 20, 30, 40]
>>> L.append(50)
>>> L
[10, 20, 30, 40, 50]
B) APPENDING A LIST OF ELEMENTS TO A LIST -
The append() method added a single element to a
list. To append a list of elements to an existing list, you can use another
list method, extend() as this -
L.extend(<list of elements>)
Where L is the list to which the passed list’s
elements will be appended. For example -
>>> L
[10, 20 , 30, 40, 50 ]
>>> L.extend([60, 70])
>>> L
[10, 20, 30, 40, 50, 60, 70]
C) INSERTING AN ELEMENT IN A LIST -
To insert a single element at a specific
position, you can use the insert() method as -
L.insert(<index>, <item>)
Where L is the list in which item is to be
inserted at given index. Consider the list x = [10, 20, 30, 40, 50] in which
you want to insert value 90 at 2nd position, i.e., index 1, so you will type
-
>>> x = [10, 20, 30, 40, 50]
>>> x.insert(1,90)
>>> x
[10, 90, 20, 30, 40, 50]
D) MODIFYING/ UPDATING ELEMENTS IN A LIST -
To update or change an element of the list in
place, you just have to assign new values to the element's index in list as per
syntax -
L[index] = <new values>
>>> L1 = [10, 20, 30]
>>> L1[2] = 80
>>> L1
[10, 20, 80]
E) DELETING ON ELEMENT FROM A LIST -
The deletion of an element can take place,
through its value or through its index in the list. You may also delete a sub
list or a list slice. For this, python makes available different functions and a
statement. Let us see how it is done.
- Deleting An Element Using Its Index/Position -
The index of an element is 1 less than its
position 1, the index is 0 for element; for position 2, the index is 1 and so
on. To delete an element using its index, us pop() as :
L.pop(<index>)
Where L is the list from which element at given
index is to be deleted. For example, given a list x = [10, 20, 30, 40 ,50], to
delete its elements at indeed 2(position 3), you may write -
>>> x.pop(2)
30
>>> x
[10, 20, 40, 50]
- Deleting An Element Using Its Value -
To delete an element using its value from a
list(say x), use the remove() method as -
L.remove(<value>)
>>> x.remove(20)
>>> x
[10, 40, 50]
- Deleting A Sub List From A List -
The del statement can be used to remove an
individual item, or to remove identified by a slice(i.e., a sublist). It is to
be used as per syntax given below -
Del list[<index>]
# to remove element at index
Del list[<start> : <stop>] # to remove elements in list slice
Consider the following example -
>>> list = [1,2,3,4,5,6,45,48,64,]
>>> del list[2]
>>> list
[1,2,4,5,6,45,48,64]
>>> del list[2:5]
>>> list
[1,2,48,64]
If you use del<listname> only, it will
delete all the elements and the list object too. After this, no object by the
name list would be existing.
F) SORTING A LIST -
For sorting a list in ascending or descending
order you can use the sort() method discussed earlier as -
L.sort() # to sort in ascending order
L.sort(reverse = true) # to sort in descending
order
[What is Sorting ? Different Types of Sorting Programs] click to know more