List
List
1
Data Structure: Sequence
• A data structure is a group of data elements that are put together under one name.
• Data structure defines a particular way of storing and organizing data in a computer so that it can be used
efficiently.
• Sequence is the most basic data structure in Python.
• In sequence, each element has a specific index. This index value starts from zero and is automatically
incremented for the next element.
• Sequence consists of some predefined functions, These functions include finding the length of a sequence,
finding the largest and smallest elements in a sequence, etc. Other operations that can be performed on a
sequence include indexing, slicing,adding, multiplying, and checking for membership.
2
Lists
• A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements.
• Each element or value that is inside of a list is called an item. Just as strings are defined as characters
between quotes, lists are defined by having values between square brackets [ ]
List_variable = [val1, val2,...]
Exampl
es:
3
Access Values in Lists
• To access values in lists, square brackets are used to slice along with the index or indices to get value stored
at that index. The syntax for the slice operation is given as, seq = List[start:stop:step]
Exampl
e:
4
Updating Values in Lists
• Once created, one or more elements of a list can be easily updated by giving the slice on the left-hand side of
the assignment operator.
• we can also append new values in the list and remove existing value(s) from the list using the append() method
and del statement respectively.
Exampl
e:
5
Examples
#collection of similar types
list_a=[1,2,3,4,5]
print(list_a)
list_b=['a','A','C','d','E']
print(list_b)
list_c=["good","morning"]
print(list_c)
6
#accessing values in a list
print("list a values are",list_a)
#first element in the list
print("first element in the list",list_a[2])
print("last element in the list",list_a[1:4])
print("list_a[1::3]",list_a[1::3])
#updating values in a list
list_a.append(200)
print("list after updating a value is:",list_a)
del list_a[2]
print("list after deleting a value is:",list_a)
7
• #Multiply
myList=[1,2,3]
print(myList*2)
• #concatenate
yourList = [4, 5, 6]
newList= myList+ yourList
print(newList) #[1,2,3,4,5,6
8
Nested Lists
Nested list means a list within another list. We have already said that a list has elements of
different data types which can include even a list.
Exampl
e:
9
Cloning Lists
If you want to modify a list and also keep a copy of the original list, then we should create a separate copy of the
list (not just the reference). This process is called cloning. The slice operation is used to clone a list.
Exampl
e:
10
Aliasing in python
• aliasing refers to multiple variables referencing the same object in
memory.
• a = [1, 2, 3]
• b = a #both a and b referencing same list object
list1=[1,2,3,4,5]
list2=[1,2,3,4,5]
print(“list1==list2”,list1==list2)
print(“list1==list2”,list1 is list2)
11
List operations
myList=[0,1,2,3,7,5,6]
print(min(myList))#min value
print(max(myList)) #max value
print(len(myList))#length
print('a' in ['a','e','i','o','u'])#in operator
print(3 not in [0,2,4,6,8])#not in operator
print(sum(myList))#sum
print(all(myList))#returns true if all elements of the list are true.
print(any(myList))#returns true if any element of the list is true
print(sorted(myList))#returns a new sorted list
12
Basic List Methods
• Python has a set of built-in methods that you can use on lists/arrays.
• The append() method adds an item to the end of the list.
• The insert() method inserts an element to the list at the specified
index.
• The index() method returns the index of the specified element in the
list.
• The remove() method removes the first matching element (which is
passed as an argument) from the list
• The extend() method adds all the elements of an iterable (list, tuple,
string etc.) to the end of the list.
13
• The count() method returns the number of times the
specified element appears in the list.
• The pop() method removes the item at the given index
from the list and returns the removed item.
• The reverse() method reverses the elements of the list.
• The sort() method sorts the items of a list in ascending or
descending order.
• The copy() method returns a shallow copy of the list. It
returns a new list. It doesn't modify the original list.
• The clear() method removes all items from the list.
14
List methods
list1.append(45) #adds an element at the end of the list
print(list1)
['a', 'bc', 87, 1.23, 45]
list1.clear()#removes all the elements
list1.clear()
list1
[]
list1=['a',"bc",87,1.23]
x=list1.copy()
print(x)
['a', 'bc', 87, 1.23] 15
• x=['a',"bc",87,1.23]
• print(x.count(87))#returns th no of elements with the
specified value
• y=["abc","xyz",30]
• print(x.extend(y))#adds the elements of list to the end of
the current list
• print(x)
• x=['a',"bc",87,1.23]
• print(x.index(87))#returns the index of the spcified value
16
• x.insert(3,20)#adds element at specified position
• print(x)
• x.reverse()
• print(x)
17
Using Lists as Stack
Stack is an important data structure which stores its elements in an ordered manner. Stack is a linear data structure
which uses the same principle, i.e., the elements in a stack are added and removed only from one end. Hence, a
stack is called a LIFO (Last-In-First-Out) data structure, as the element that was inserted last is the first one to be
taken out.
18
19
Using Lists as Stack
Exampl
e:
20
Using Lists as Queues
Queue is an important data structure which stores its elements in an ordered manner.
• Handling interrupts.
• Queues are also used in the playlist of jukebox to add songs to the end and play from the front of the list.
Queue supports three basic operations—insert, delete, and peep (or peek). In Python, you can easily implement a
queue by using the append() method to insert an element at the end of the queue, pop() method with an index 0
to delete the first element from the queue, and slice operation to print the value of the last the element in the
queue.
21
Using Lists as Queues
Exampl
e:
22
List Comprehensions
Python also supports computed lists called list comprehensions having the following syntax.
List = [expression for variable in sequence]
Where, the expression is evaluated once, for every item in the sequence.
List comprehensions help programmers to create lists in a concise way. This is mainly beneficial to make new
lists where each element is the obtained by applying some operations to each member of another sequence or
iterable. List comprehension is also used to create a subsequence of those elements that satisfy a certain
condition.
Exampl
e:
23
examples
• list=[i for i in range(11) if i%2==0]#even
• print(list)
• print([(x,y) for x in [10,20,30] for y in [30,10,40] if x!=y])#combine and print two lists
using list comprhension
25
Looping in Lists
Python's for and in constructs are extremely useful especially when working with lists. The for var in list statement is an easy
way to access each element in a list (or any other sequence). For example, in the
following code, the for loop is used to access each item in the list.
for i in list: Exampl
e:
print(i)
enumerate() function is used when you want to print both index as well as an item in the list. The function returns
an enumerate object which contains the index and value of all the items of the list as a tuple.
The range() function is used when you need to print index.
Exampl
es:
27
Using an Iterator
You can create an iterator using the built-in iter() function. The iterator is used to loop over the elements of the
list. For this, the iterator fetches the value and then automatically points to the next element in the list when it is
used with the next() method.
Exampl
e:
• #Python List/Array
• l1 = [] # defined an empty list
• l5=list() # defined an empty list
• l2 = [5,43,6,1]# define a list of 4 elements
• l3 = [[4,3],[0,1],[3]]# define a list of 3 elements(lists)
• l4 = [1,"sat",2]
• print("l1={},l5={}".format(l1,l5))
• print("l2[0]=",l2[0])
29
print("l2[3]=",l2[3])
print("l2[-2]=",l2[-2])
print("l2[1:3]=",l2[1:3])
print("l3[1]=",l3[1])
print("l3[1][1]=",l3[1][1])
print("l4[1]=",l4[1])
print("l4[1][1]=",l4[1][1])
30
filter() Function
The filter() function constructs a list from those elements of the list for which a function returns True. The
syntax of the filter() function is given as, filter(function, sequence)
As per the syntax, the filter() function returns a sequence that contains items from the sequence for which the function is True.
If sequence is a string, Unicode, or a tuple, then the result will be of the same type;
otherwise, it is always a list.
Exampl
e:
31
map() Function
The map() function applies a particular function to every element of a list. Its syntax is same as the filter function
After applying the specified function on the sequence, the map() function returns the modified list. The map()
function calls function(item) for each item in the sequence and returns a list of the return values.
32
reduce() Function
The reduce() function with syntax as given below returns a single value generated by calling the function
on the first two items of the sequence, then on the result and the next item, and so on.
Example: Program to calculate the sum of values in a list using the reduce()
function
33
Cloning Lists (Copying Lists) Different Ways to copy list:
34
#Using the method of Shallow Copy
import copy
# initializing list 1
L1 = [4, 8, 2, 10, 15, 18]
# using copy for shallow copy
L2 = copy.copy(L1)
print(L2)
Like lists, tuple is another data structure supported by Python. It is very similar to lists
but differs in two things.
• First, a tuple is a sequence of immutable objects. This means that while you can
change the value of one or more items in a list, you cannot change the values in a tuple.
• Second, tuples use parentheses to define its elements whereas lists use square
brackets.
Creating Tuple
Creating a tuple is very simple and almost similar to creating a list. For creating a tuple,
generally you need to just put the different comma-separated values within a
parentheses as shown below.
Tup1 = (val 1, val 2,...)
© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED. 38
where val (or values) can be an integer, a floating number, a character, or a string.
Utility of Tuples
In real-world applications, tuples are extremely useful for representing records or
structures as we call
in other programming languages. These structures store related information about a
subject together.
The information belongs to different data types.
For example, a tuple that stores information about a student can have elements like
Exampl name, course, total marks, avg, etc. Some built-in functions return a tuple. For
roll_no,
es:
example, the divmod() function returns two values—quotient as well as the remainder
after performing the divide operation.
Exampl
es:
Exampl
es:
Exampl
es:
The zip() is a built-in function that takes two or more sequences and "zips" them into a
list of tuples. The tuple thus, formed has one element from each sequence.
• Tuples are used to store values of different data types. Lists can however, store data
of similar data types.
• Since tuples are immutable, iterating through tuples is faster than iterating over a list.
This means that a
tuple performs better than a list.
• Tuples can be used as key for a dictionary but lists cannot be used as keys.
• Tuples are best suited for storing data that is write-protected.
• Tuples can be used in place of lists where the number of values is known and small.
• If you are passing a tuple as an argument to a function, then the potential for
unexpected behavior due to
aliasing gets reduced. © OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS
RESERVED. 49
• Multiple values from a function can be returned using a tuple.
Sets
Sets is another data structure supported by Python. Basically, sets are same as lists but
with a difference that sets are lists with no duplicate entries. Technically, a set is a
mutable and an unordered collection of items. This means that we can easily add or
remove items from it.
A set is created by placing all the elements inside curly brackets {}, separated by comma
or by using the
built-in function set(). The syntax of creating a set can be given as,
Example: To create a set, you can write,
Exampl
e:
Exampl
e:
Python also allows you to use string formatting feature with dictionaries. So you can use
%s, %d, %f, etc. to
represent string, integer, floating point number, or any other data.
Example: Program that uses string formatting feature to print the key-value pairs stored in the
dictionary
• Use lists to store a collection of data that does not need random access.
• Use lists if the data has to be modified frequently.
• Use a set if you want to ensure that every element in the data structure must be
unique.
• Use tuples when you want that your data should not be altered.