List
List
Sequences allow you to store multiple values in an organized and efficient fashion. Or we can say that A Sequence is
an ordered collection of items, indexed by positive integers. It is a combination of mutable (a mutable variable is one,
whose value can be changed) and immutable (an immutable variable is one, whose value cannot be changed) data
types.
There are seven sequence types: strings, Unicode strings, lists, tuples, bytearrays, buffers, and xrange objects.
Dictionaries and sets are containers for sequential data.
Lists
If we want to represent a group of individual objects as a single entity where insertion order preserved and
duplicates are allowed, then we should go for list. Lists are related to arrays of programming languages like C, C ++ or
Java, but Python lists are by far more flexible and powerful than "classical" arrays.
A list is a collection of multiple values stored in a sequence. It is one of the most used datatypes in Python.
All the items in a list do not need to be of the same type. Values in the list are called elements/items.
Each element of the list can be accessed by using it's index number.
The list type is essential for Python scripts and programs; this means that you will hardly find any serious Python
code without a list.
You can create a list objects In Python programming through various methods given below. You will see that a
list is created by placing all the items (elements) inside a square bracket [], separated by commas they may be of
different types (integer, float, string etc.).
>>> list = [ ]
>>> print(list)
[]
>>> print (type (list))
<class ‘1ist’ >
2. Create list with elements
>>> list=[10,20,30,40]
>>> print (list)
[10, 20, 30, 40]
>>> list =[‘a’,’b’,’c’,’d’,’e’]
>>> print (list)
[‘a’,’b’,’c’,’d’,’e’]
>>> list=[True, False ]
>>> print(list)
[True, False]
# Test.py
list = eval (input ("Enter List:"))
print (list)
Output:
Enter List:[10,20,30,40]
[10, 20, 30, 40]
Output:
Output:
Output:
Multi-Dimensional List:
[['Apple', 'Banana'], ['Onion', 'Potato'])
Output:
Output:
Syntax: list([iterable])
Return value from list(): The list() function returns a mutable sequence list of elements.
Example:
# empty list
print(list())
# string
s = 'Be a Master'
print (list(s))
# vowel list
List = ['a', 'e', 'i', 'o', 'u']
print(list(List))
Ouput:
In Python, you may need to break a large string down into smaller strings then we use the split function.
What it does is split a string and add the data to a string array using a defined separator. By default separator is
whitespace.
separator (optional): This parameter specifies the delimiter character or substring based on which the string will
be split. If not provided, the `split()` method uses whitespace (spaces, tabs, and newlines) as the default
delimiter.
maxsplit (optional): This parameter specifies the maximum number of splits to be performed. If specified, the
resulting list will have at most `maxsplit + 1` elements. If not provided, all occurrences of the delimiter will be
considered for splitting.
Return Value from split(): The split() breaks the string at the separator and returns a list of strings.
Example 1:: Python code to break the string at the different-different separator point.
str3 = “1:2:3:4:5:6:7:8:9”
# Splitting at :
print (str3.split(‘:’))
Example 2: Python code to break the string at the separator point comma(,).
using max-split
nums=’1, 2, 3, 4, 5, 6, 7, 8, 9’
# maxsplit: 2
print (nums.split (‘, ‘, 2 ))
# maxsplit: 1
print (nums.split (‘, ‘, 1 ))
maxsplit: 5
print (nums.split (‘, ‘, 5 ))
# maxsplit: 0
print (nums.split (‘, ‘, 0 ))
Example 4:
# maxsplit: 2
print (grocery.split (‘, ‘, 2 ))
# maxsplit: 1
print (grocery.split (‘, ‘, 1 ))
maxsplit: 5
print (grocery.split (‘, ‘, 5 ))
# maxsplit: 0
print (grocery.split (‘, ‘, 0 ))
Accessing elements from the List
Indexing
For accessing an element of the list, indexing is used. Each item in a list corresponds to an index number,
which is an integer value, starting with the index number 0 goes to (length -1). So, a list having 5 elements will have
an index from 0 to 4. We can't use float or other types; this will result in TypeError. We can use indexing to change
items within the list, by setting an index number equal to a different value.
We can use the square brackets (index operator []) for slicing along with the index or indices to obtain value
available at that index. Nested list is accessed using nested indexing.
Positive index: Positive index means starts from left to right (0 to n) (forward direction). The first index has 0; the
next index has 1, and so on. The last index will be the length of the list minus one.
Negative index: Negative index means starts from right to left (- 1to - n) (backward direction).The first index has -1;
the next index has -2, and so on. The last index will be the length of the list.
Note: - The sequentical accesing of each element in a list is called traversing. This can be done by using either for or
while loop statements. In for or while loop statement 'in' operator used to iterate each element of a list in sequence.
Note: In the above program len function is used to find the length of list.
Slicing
We use indexing to access individual elements but we can use slicing to access a range of items in a list by
using the slicing operator : (colon). Slicing is very useful for extracting certain elements from a list and forms them
into another list, possibly with different number of indices and different index ranges. The syntax for list slicing is as
follows:
Start->Start position
Stop-->End position
Step-->Increment Specify Step of the Slicing.
Example1:
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
10 20 30 40 50 60 70 80 90 100
num=[ 10, 20, 30, 40, 50, 60, 70, 80 ,90,100]
num1= num[3:8]
0 1 2 3 4 5 6 7 8 9
print(numl)
In our example start equals 3, so our slice starts from value 40. stop is 8, so the last element of the slice is 80,
here we are passing +Ve index, then it should be from left to right forward direction (3 to 8 - 1). In the end, slice
creates a new list (we named it num1) with selected elements.
Example 2:
print (num[:7])
print (num[4:1])
print (num[::])
Output:
Note:
1. If index is invalid in indexing process, we get index out of range error, where as in slicing never get index error.
2. In slicing, end index is bigger than 'end index -1', PVM will take up to the last position character only.
Example 3:
print(num[4:70])
print(num[-11:-100])
print(num[-2:10])
Output:
[90, 100]
Note:
1. Step value can be +ve or-ve, but cannot be zero otherwise PVM gives an error message.
For example:
For example:
>>> no = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(no[::1])
[1, 2, 3, 4, 5, -6, 7, 8, 9]
[1, 3, 5, 7, 9]
>>> print(no[-6:8])
[4, 5, 6, 7, 8]
3. If-ve then it should be from right to left backward direction (-1 to –(end+1)).
For example:
>>> no = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print (no[::-1])
[9, 8, 7, 6, 5, 4, 3, 2, 1]
[9, 7, 5, 3, 1]
[2, 3, 4]
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:
>>> no{::4}
[1,5,9]
Example 4:
>>> no = [1, 2, 3, 4, 5, 6, 7, 8, 9]
To Access the elements from the list, we also use range function. The range() gives a sequence of numbers in
between the two integers given to it. The combination of the for-loop and the range function allow you to build a
traditional numeric for loop:
i=5
for i in range (i, 10, 1)
print (i)
# Python program to demonstrate
# Creating a List
List = ['G', 'E', 'E', 'K', 'S', 'F','O', 'R', 'G', 'E', 'E', 'K', 'S']
print(List)
Sliced_List = List[3:8]
print(Sliced_List)
Sliced_List = List[5:]
print(Sliced_List)
Sliced_List = List[:]
print(Sliced_List)
# Creating a List
List = ['G', 'E', 'E', 'K', 'S', 'F','O', 'R', 'G', 'E', 'E', 'K', 'S']
print(List)
Sliced_List = List[:-6]
print(Sliced_List)
Sliced_List = List[-6:-1]
print(Sliced_List)
Sliced_List = List[::-1]
print(Sliced_List)
Adding Elements to a List
There are following functions used to add Element to the list.
1. append(): In Python, elements can be added to the List by using built-in function append(). Only one element at
a time can be added to the list by using append() method, for addition of multiple elements with the append()
method, loops are used. append() method added of elements at the end of the list.
2. insert(): append() method only works for addition of elements at the end of the List, for addition of element at
the desired position, insert() method is used. Unlike append() which takes only one argument, insert() method
requires two arguments (position, value).
3. extend(): This method is used to add multiple elements at the same time at the end of the list.
Note: append() and extend() methods can only add elements at the end.
1st =[]
print ("Blank List: ")
print (lst)
lst.append(10)
lst.append(30)
lst.append(50)
print ("After Addition of Three elements: ")
print (lst)
Example 2:Adding Multiple elements to the List using loop at the same time
lst =[]
for i in range (10, 20):
lst.append(i)
print("After Addition of elements from 10-19: ")
print(lst)
a =[]
for i in range (1, 4) :
a.append(i)
print("\nList after Addition of elements from 1-3:”)
print(a)
b = [‘apple’, ‘boy’]
b.append(a)
print("List after Addition of a List: ")
print (b)
lst = [1, 2, 3, 4, 5]
lst.extend ([6, 7, 8])
print ("List after performing Extend Operation: ")
print (lst)
1. remove(): The remove() method searches for the given element in the list and removes the first matching
element. If the item present multiple times, then only first occurrence will be removed.
remove() method only removes one element at a time, to remove range of elements, iterator is used.
remove() function raises an Error if element doesn't exist in the set.:
Syntax: list.remove(element):
The remove() method takes a single element as an argument and removes it from the list.
If the element(argument) passed to the remove() method doesn't exist, valueError exception is thrown.
The remove doesn't return any value.
Example 2: If the specified element not present in list we will get an error message.
Example 3:If the item present multiple times then only first occurrence will be removed
2. pop(): pop() function can also be used to remove and return an element from the set, but by default it
removes only the last element of the set, to remove element from a specific position of the List, index of the
element is passed as an argument to the pop() method.
Syntax: list.pop(index)
The pop() method takes a single argument (index) and removes the item present at that index.
If the index passed to the pop() method is not in range, it throws IndexError: pop index out of range
exception.
The parameter passed to the pop() method is optional. If no parameter is passed, the default index -1 is
passed as an argument which returns the last item.
Example 1:
lst = [10,20,30]
print (lst)
lst.pop()
print (lst)
lst.pop()
print (lst)
lst.pop()
print (lst)
Example 2: If the list is empty then pop() function raises an error message.
lst =[]
print(lst)
lst .pop()
remove() Pop()
pop() takes an index as its argument and will remove the element
remove() takes an element as its argument
and removes it if it's in the list, otherwise an at that index. If no argument is specified, pop will remove the last
exception will be thrown. element. pop() also returns the element it removed.
remove () it delete the matching pop removes the element at a specific index or by default last
element/object. element.
It can't return any value. It returned remove element.
It throws value error in case of value doesn't
It throws index error in case of an index doesn't exist in the list.
exist in the list
Note: List objects are dynamic i.e., based on our requirement we can increase and decrease the size.
Example:
>>>print(x)
[]
del statement:-It is used to remove specific items from the list or to remove all items identified by a slice. To delete a
single element from a python list, use its index and use the slicing operator to delete a slice.
Example:
1. sort(): The sort() method sorts the elements of a given list in a specific order - Ascending or Descending. It
doesn't return any value.
Syntax: list.sort()
or
list.sort(key=..., reverse =...)
In the above syntax:
key- To specify a function (or other callable) to be called on each list element prior to making comparisons.
reverse- If true, the sorted list is reversed (or sorted in Descending order)
Example 1:
>>> x = [2, 5, 3, 90, 12, 67]
>>> x. sort ()
>>> X
[2, 3, 5, 12, 67, 90]
>>> x = [3, 2, 5, 1, 4]
>>>y=x.sort() # Don't do this!
>>>print (y)
None
Since sort () modifies x but returns nothing, you end up with the sorted and the 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 shown below:
>>> x = [3, 2, 5, 1, 4]
>>>y=x[:] # x [:] is a slice containing all the elements of x, effectively a copy of the entire list.
>>>y.sort()
>>>x
[3, 2, 5, 1, 4]
>>>y
[1, 2, 3, 4, 5]
If the Python list members are strings, it sorts them according to their ASCII values.
>>>y = ['zebra', 'pink', 'apple', 'boy']
>>> y.sort()
>>> print (y)
['apple', 'boy', 'pink', 'zebra']
>>> print (y.sort()) #sort() doesn't return any value, so that none is the result.
None
Output:
Original list : [70, 50, 60, 1, 20]
Sorted (Descending order) list: [70, 60, 50, 20, 1]
Alternatively, you can also use Python's in-built function sorted() for the same purpose.
Example 4:
nums=[70,50, 60,1,20]
print ("Original list : ", nums)
print('Sorted (Ascending order) list:’, sorted (nums))
Output:
Original list: [70, 50, 60, 1, 20]
Sorted (Ascending order) list: [1, 20, 50, 60, 70]
Output:
Original list: [70, 50, 60, 1, 20]
Sorted (Descending) list: [70, 60, 50, 20, 1]
Note: In Python 2 if list contains both numbers and strings then sort() function first sort numbers and followed by
string. But in Python 3 it is invalid.
Example 6: If list contains both numbers and strings then sort() and sorted() raises an error message.
nums=['apple', 50, 60, 'banana", 20]
print("Original list : ", nums)
nums.sort()
print('Sorted list : ‘, nums)
Output:
Original list: ['apple', 50, 60, 'banana', 20]
Traceback (most recent call last):
File "C:/Python37/practice/test.py", line 3, in <module>
nums.sort()
TypeError: '<' not supported between instances of int' and 'str'
Note:
10 20 ‘zero’ ‘one’
y
16]::[10, 12, 13, 15]::4. count(obj):-It returns count of how many times obj occurs in list.::Syntax:-
List.count(obj)::Example:-::>>> list = [22, 11, 44, 22, 21]::>>>list. count(22)::2:5.1.8 Aliasing and Cloning of
List objects::The process of giving another reference variable to the existing list is called aliasing. Example
1::x=[10,20, prime zer * o' ,^ prime one^ prime ]::y = x::print ("id of x:", id (x))::print ("id of y : ", id
(y))::Output:::id of x:::45409664::id of y:::45409664:The problem in this approach is by using one reference
variable if we are changing content, then those changes will be reflected to the other reference
variable.:Example 2:::x=[ 10, 20 , ' zer * o' , 'one']::y = x::print ("id of x: "::, id (x)) print ("id of y: ", i *
d(y) )::y[0] = 30::print (y)::print (x)::Output:::id of x: 45606272::45606272 id of y: 45606272::[30, 20, 'zero',
'one'] zero', ' one']::[30, 20, ':To overcome this problem we should go for cloning. The process of creating
exactly duplicate independent object is called cloning. We can implement cloning by using slice operator or
by using copy function.:Example 3: By using slice operator::x = [10, 20, 30]::y =x[:]::print ("id of x: ", id
(x))::print ("id of y: ", id (y))::y[1] = 15::print (y)::print (x)::id of x: 45409544::Output:::id of y: 45409224::[10,
15, 30] [10, 20, 30]::Example 4:::by using copy() function::x = [10, 20, 30] y=x. copy ()::print ("id of x: ", id(x))
print("id of y: ", id (y))::y[1] = 15::print (y)::print (x)::Output:::id of x: 45147360::Lid id of y: 45147040 [10, 15,
30]::[10, 20, 30]:Note: Difference between '=' operator and copy() function: '=' operator meant for aliasing
and copy function meant for cloning(). 5.1.9 Using mathematical operators for
list objects In Python, we can use '+' and '*' operators for list
objects.:Concatenation operator(+): We can use '+' operator to
concatenation 2 lists into a single list.::Example:::x = [10, 20, 30] y = [40,
50, 60]::z = x + y print(z)::Output: [10, 20, 30, 40, 50, 60]::Note: To use
'+' operator compulsory both arguments should be list type objects, otherwise we will get TypeError
message.::Example:::>>> x = [10, 20]::>>> y = x + 20 marble maps Ballestado Traceback (most recent call
last):::File "<pyshell#85", line 1, in <module>::y = x + 20::TypeError: can only concatenate list (not "int") to list
>>> y = x + [30]::[10, 20, 30]::2. Repetition operator (*): We can use repetition operator to repeat elements of
list specified::number of times.::x = [10, 20, 30]::z = x + 3::Example:::print(z)::Output:::[10, 20, 30, 10, 20,::30,
10, 20, 30]::5.1.10 Comparing list objects::We can use comparison operators for list objects.::Example 1:::x =
[10, 20, 30]::y = [10, 20, 30] z = [20, 30, 10] print ( x ==z)::print (x==v)::pzint(x! = z)::Output:::True::False
True::be considered.::il vol a Note: Whenever we are using comparison operators (==,!=) for list objects then
the following should::The number of elements.:The order of elements.:The content of elements (case
sensitive).:Example:::x=[^ prime a' ,^ prime b^ prime ,^ prime c^ prime ] y=[^ prime a' ,^ prime b^ prime ,^
prime c^ prime ] z=[^ prime A' ,^ prime B^ prime ,^ prime C^ prime ]::print ( x ==y) vrint (x==z)::print (x! =
z)::Output:::True::False::True::Note: whenever we are using relational operators (<,<=,>,>=) between list
objects, Then only first element comparison will be performed.::Example:::x=[^ prime a' ,^ prime b^ prime ,^
prime c^ prime ]::y=[^ prime a' ,^ prime b^ prime ,^ prime c^ prime ]::z=[^ prime A' ,^ prime B^ prime ,^
prime C^ prime ]::print(x > y)::print (x >= z)::print(x < z)::print(z <
x)::Output:::False::True::False::True::Membership Operator for list objects::5.1.11::In Python, we can check
whether element is a member of the list or not by using membership operators. Membership operators are
'in' and 'not in'. Python's membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below-
X===> 10 20 30
Operator Description Example
Y===> 10 It 20
In 15 30
evaluates to true if it finds a variable in the x in y, here if x is a member of sequence y.
specified sequence and false otherwise. Then results will be 1.
not in It evaluates to true if it does not finds a Ivariable in x not in y, here if x is not a member of
the specified sequence and false otherwise. sequence y. Then results will be 1.
Example:::x=[^ prime a' ,^ prime b^ prime ,^ prime c^ prime ]::print (^ prime a' * inx )::print (^ prime d' *
inx )::print('b' not in x) print('e' not in x):Output:::True::False::False::True:5.1.12 Nested Lists:Sometimes we can take
one list inside another list. Such types of lists are called nested lists. :Example: :a = [10, 20, [30,
40]] :print (a) :print (a[0]) :print (a[1]) :print (a[2]) :print (a[2][0]) :print (a [2]
[1]):Output::[ 10, 20, [30, 401]:10::20 [30, 40] 30 40:Note: We can access nested list elements by using index just like
accessing multidimensional array elements. In Python, we can represent matrix by using nested lists.:Example:::a =
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]::print (a)::print ("printing elements by row wise")::for i in a:::print (i)::print ("printing
elements by matrix style") for i in range (len (a)) :::for i in range (len (a[i])): print (a[i][j], end="") print():Output:::[[1,
2, 3], [4, 5, 6], [7, 8, 9]]::printing elements by row wise::[1, 2, 3]::[4, 5, 6]::[7, 8, 9]::printing elements by matrix
style::1::2 3::4 5 6::7 8 9:5.1.13 Comprehension::Comprehensions in Python provide us with a short and concise way
to construct new sequences (list, dictionary, set and generator) using sequences which have been already
defined.::5.1.13.1 List comprehension::List Comprehensions provide an elegant way to create new lists. The following
is the basic structure of a list comprehension: output_list = [output_expression for var in input_list if (var satisfies this
condition)]::Note: The list comprehension may or may not contain an if condition. List comprehensions can contain
multiple for (nested list comprehensions).::Example: Suppose we want to create an output list which contains
squares of all the numbers from 1 to 10.::list =[]::for a in range (1, 11):::list.append ( a **2) print ("Output : ", list)
print (type (list))::Output:::Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] <class 'list'>::::