SlideShare a Scribd company logo
Module3
LISTS
Prof. Krishnananda L
Department of ECE
Govt SKSJTI
Bengaluru
Contents:
Introduction
Features
The list constructor ( ):
List slicing
Replace list items
Check if item exists in a list
Loop list
List comprehension
Built-in function
List methods
List operation
Unpacking list.
PYTHON DATA TYPES
Python supports 3 sequence data types:
1. LISTS
2. TUPLES
3. STRINGS
Other two important data structures in Python are:
1. SET
2. DICTIONARY
List is a collection which is ordered , mutable and indexed
Lists are created by square brackets and the elements in the list are separated
by commas.
Lists are used to store multiple items in a single entity.
Lists allow duplicates
LIST:
# exampleof lists
>>>games=['cricket','badminton','volleyball']
>>>print (games)
['cricket', 'badminton','volleyball']
>>>List=[1,2,,3,4,]
>>>print(List)
[1, 2, 3, 4]
List items are ordered means, items can be accessed using positional index. In general, new items
will be placed at the end of the list.
#Lists allow duplicate values:
>>>games=['cricket','badminton','volleyball','cricket','volleyball']
>>>print(games)
#output
['cricket','badminton', 'volleyball', 'cricket', 'volleyball']
>>> len(games)
5
Lists are mutablemeans we can change, add and remove items in a list after it has been created.
Since the list is indexed , lists can have items with same value.
Ordered:
Mutable:
Allows duplicate:
1. List can contain elements of different data types i.e., string , int, Boolean, tuple etc. Lists are
Mutable
Features:
>>>list=['cricket','abc',42,29, 0, True]
>>>print(list)
#output
['cricket','abc', 42,29, 0, True]
>>>list=['cricket','abc',42,29.0,True]
>>>print(type(list))
#output
<class 'list'>
>>> list =[23, 45, 'krishna', (34,56)]
>>> print (list)
[23, 45, 'krishna', (34, 56)]
2. Lists are defined as objects with the data type ‘list’.
>>> list[1]='hello‘ ## mutability
>>> print (list) ## same memory reference
[23, 'hello', 'krishna', (34, 56)]
>>> list[3]=(89,'welcome')#mutability
>>> print (list)
[23, 'hello', 'krishna', (89, 'welcome')]
>>>len(list)
>>> list =[23, 45, 'krishna', (34,56)]
>>> print (list[2])# accessing list element
krishna
Lists Vs Tuples
The list constructor ( ) :
It is also possible to use the
list ( ) constructor when
creating a new list.
x=list(('cricket','abc',42,29.0,True))
"""note
the double round-brackets"""
print(x)
#output:
['cricket','abc', 42,29.0, True]
Simple Operations on Lists
>> list1=[23, 55,77]
>>> list2=[23, 55, 77]
>>> list1==list2
True
>>> list1 is list2
False
>>> list2=list1
>>> list2 is list1
True
>>> d1=['a','b','c']
>>> d2=['a','b','d']
>>> d1<d2
True
>>> min(d1)
'a'
>>> max(d2)
'd‘
>>> sum(list1)
>>> list1=[20, 'hi', 40]
>>> list2=[20, 40, 'hi']
>>> list1==list2
False
>>> list1>list2
Traceback (most recent call last):
File "<pyshell#16>", line 1, in
<module>
list1>list2
TypeError: '>' not supported
between instances of 'str' and 'int'
>>> ["abc"]>["bac"]
False
>>> [45, 67, 89] + ['hi', 'hello']
[45, 67, 89, 'hi', 'hello']
Assignment and References
>>>x = 3
• First, an integer 3 is created and stored in memory
• A name x is created
• A reference to the memory location storing 3 is then
assigned to the name x
• So: When we say that the value of x is 3, we mean
that x now refers to the integer 3
Ex with immutable data like integers:
>>> x=10 # Creates 10, name x refers to 10
>>> y=x # Creates name y, refers to 10.
>>> id(x)
1400633408
>>> id(y) # x and y refer to same location
1400633408
>>> print(y)
10
>>> y=20 ## creates reference for 20
>>> id(y) ### changes y
1400633568 ## y points to a new mem location
>>> print (y)
20
>>> print(x) # no effect on x. Refers to 10
10
Note: Binding a variable in Python means
setting a name to hold a reference to some
object.
• Assignment creates references, not copies
 x = y does not make a copy of the object y
references
 x = y makes x reference the object y
references
List Assignment
>>> d=[1,2,3,4] ## d references the list [1,2,3,4]
>>> id (d)
56132040
>>> b=d ## b now references what d references
>>> id(b)
56132040
>>> b[3]=10 ## changes the list which b references
>>> print (b)
[1, 2, 3, 10]
>>> print (d) ### change reflected in original also
[1, 2, 3, 10]
>>>a=[23, 45, 'hi']
>>> b=a # two names refer to same memory
>>> id(a)
24931464
>>> id(b)
24931464 ## only one list. Two names refer to it
>>> a.append('welcome') ## change list element
>>> id(a)
24931464 # refer to same object
>>> print (a) [23, 45, 'hi', 'welcome']
>>> print (b)
## Change in one name affects the other
[23, 45, 'hi', 'welcome']
Lists are “mutable.”
When we change the values of list elements,
we do it in place.
We don’t copy them into a new memory
address each time.
If we type y=x and then modify y, both x
and y are changed
Note: b=a[:] creates copy of list a. Now we have
two independent copies and two references
List Slicing:
x=list(('cricket','abc',42,29.0,True))
print(x[-1])
print(x[2])
print(x[0])
#Output:
True
42
cricket
Positive indexing 0 1 2 3 4
List Cricket abc 42 29.0 True
Negative indexing -5 -4 -3 -2 -1
Note: Slicingis helpful to get a subset of the
original list
 Range of positive indexes:
We can specify a range of indexes by specifying where to start and where to end
the range.
# RETURN THE THIRD ,FOURTH AND FIFTH TERM:
>>>x=['cricket','badminton','volleyball','football','hockey','cheese']
print(x[2:5])
#output:
['volleyball', 'football', 'hockey']
2 3 4 Index number
NOTE: 1) The search will start at Index 2 ( included) and end at index 5 (not included).
2)Remember that the first item has index 0.
3)The index ranges from 0 to (n-1).
By leaving out the start value, by default the range will start
at the first item.
x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle']
print(x[:4])
#output:
[‘cricket’,’badminton’,’volleyball', 'football']
By leaving out the end value, by default the range will go
on to the end of the list.
x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle']
print(x[2:])
#output:
['volleyball', 'football', 'hockey', 'shuttle']
Herehockeyhasa
index value 4 and
isexcluded
becausetherange
isfrom0:(n-1)
0:(4-1)
i.e.,0:3
Herevolleyball hasa
index value 2 andis
included becausethe
range isfrom 2: last
itemin thelist
If you want to search the item from the end of the list , negative indexes can be
used.
>>>x=['cricket', 'badminton', 'volleyball',
'football','hockey', 'shuttle']
print(x[-3:-1])
#output:
['football', 'hockey']
-6 -5 -4
-3 -2 -1
Here the range is from
-3(included) : -1(excluded).
Shuttle is excluded because of
the range of index(-1).
 Range of negative indexes:
To replace the value of a specific item ,refer to the index number.
 Replace/Modify items in a List
#CHANGE THE SECOND ITEM IN A LIST:
x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle']
x[2]='PUBG‘
print(x)
#output:
['cricket', 'badminton', 'PUBG', 'football', 'hockey', 'shuttle']
Here volleyballis
replacedbyPUBG
• Replace a range of elements
To replace the value of items within a specific range, define a list with the new
values, and refer to the range of index numbers where you want to insert the new
values.
x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle']
x[4:]='PUBG','FREEFIRE’
print(x)
#Output:
['cricket', 'badminton', 'volleyball', 'football', 'PUBG', 'FREEFIRE']
We can also replace this line
by
x[4:6]=[‘PUBG,’FREEFIRE’]
If you insert more items than you replace , the new items will be inserted where you
specified, and the remaining itemsmove accordingly.
>>>x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle']
>>>len(x)
6
>>>x[2:3]='PUBG','FREEFIRE’
>>>print (x)
>>>len(x)
7
['cricket', 'badminton', 'PUBG', 'FREEFIRE', 'football', 'hockey', 'shuttle']
If you insert less items than you replace , the new items will be inserted where you specified,
and theremaining items move accordingly.
>>>x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle']
>>>x[2:4]=['PUBG']
print(x)
#Output:
['cricket', 'badminton', 'PUBG', 'hockey', 'shuttle']
Note: If the range of index which must be replaced is not equal to the item to be
replaced, the extra mentioned range of item is removed from the list … i.e., in the
range x[2:4] we can replace 2 items but we replaced only 1 item PUBG, hence
football is removedin the list.
Here square brackets are
must and necessary. If not
used the single item PUBG is
BY DEFAULT taken as 4
individual item as ‘P’,’U’
,’B’,’G’.
>>> list=[] #emptylist
>>> len (list)
0
>>> type(list)
>>> list=[34 ] # list with single element
>>> len (list)
1
>>> type(list)
<class 'list'>
x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle']
x[2:4]='PUBG'
print(x)
#Output:
['cricket', 'badminton', 'P','U', 'B', 'G', 'hockey', 'shuttle']
Here squarebrackets are
notusedhence the single
item PUBG is BY
DEFAULTtakenas 4
individualitemas‘P’,’U’
,’B’,’G’.
NOTE : The length of the list will change when the number of items
inserteddoes not match thenumber of itemsreplaced.
 Check if item exists in a list:
To determine if a specified item is present in a list use the in keyword.
x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle']
if 'volleyball' in x:
print(“yes, ‘volleyball’ is in the list x”)
#output:
yes ‘volleyball’ is in the list x
List Comparison, use of is, in operator
>>> l1=[1,2,3,4]
>>> l2=[1,2,3,4]
>>> l3=[1,3,2,4]
>>> l1==l2
True
>>> l1==l3
False
>>> id(l1)
1788774040000
>>> id(l2)
1788777176704
>>> id(l3)
1788777181312
>>> l1 is l2
False
>>>> l1=['a','b','c','d']
>>> l2=['a','b','c','d']
>>> l1 is l2
False
>>> l1==l2
True
>>> if 'a' in l1:
print (" 'a' is present")
'a' is present
>>> if 'u' not in l1:
print (" 'u' is not present")
'u' is not present
Loop Through a List
You can loop through the list items by using
a for loop:
Loop list:
fruits=['apple','cherry','grapes']
for x in fruits:
print(x)
#Output:
apple
cherry
grapes
 Loop Through the Index Numbers
• You can also loop through the list
items by referring to their index
number.
• Use the range() and len() functions
to create a suitable iterable.
fruits= ["apple", "banana", "cherry"]
for i in range(len(fruits)):
print(fruits[i])
#Output:
apple
banana
cherry
 Using a While Loop:
• You can loop through the list items by using a while loop.
• Use the len() function to determine the length of the list, then start at 0 and
loop your way through the list items by referring to their indexes.
• Update the index by 1 after each iteration.
thislist = ["apple", "banana", "cherry"]
i = 0
while i < len(thislist):
print(thislist[i])
i = i + 1
#Output:
apple
banana
cherry
thislist = ["apple", "banana", "cherry"]
[print(x) for x in thislist]
#Output:
apple
banana
cherry
 Looping Using List Comprehension:
List Comprehension offers the shortest syntax
for looping through lists:
List Comprehension:
List comprehension offers a shorter syntax when you want to create a new list
based on the values of an existing list.
Example:
• Based on a list of fruits, you want a new list, containing only the fruits with the
letter "a" in the name.
['apple', 'banana', 'mango']
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [ ]
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
#Output:
• Without list comprehension you will have to write a for statement with a
conditional test inside:
This line specifies
that the newlist must
appendonlythe
fruits whichcontains
the letter‘a’ in them.
• With list comprehension one line of code is enough to create a new list:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruitsif "a" in x]
print(newlist)
#Output:
['apple', 'banana', 'mango']
• The Syntax:
newlist = [expression for item in iterable if condition == True]
• Condition:
The condition is like a filter that only accepts the items that evaluates to True.
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if x != "apple"]
print(newlist)
#Output:
['banana', 'cherry', 'kiwi', 'mango']
The
condition if x!= "apple" will
return True for all elements
other than "apple", making the
new list contain all fruits
except "apple".
Note: The iterable can be any iterable object, like a list, tuple, set etc.
Note: The expression is the
current item in the iteration, but
it is also the outcome, which you
can manipulate before it ends up
like a list item in the new list
Some examples of List Comprehension
>>> newlist = [x for x in range(10)]
>>> print (newlist)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
>>> newlist = [x for x in range(10) if x < 5]
>>> print (newlist)
[0, 1, 2, 3, 4]
>>> list1=['cricket','badminton', 'volleyball', 'football','hockey']
>>> newlist = [x.upper() for x in list1]
>>> print (newlist)
['CRICKET', 'BADMINTON', 'VOLLEYBALL', 'FOOTBALL', 'HOCKEY']
>>> newlist1 = ['welcome' for x in list1]
>>> print (newlist1)
['welcome', 'welcome', 'welcome', 'welcome', 'welcome']
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list (creates a new list with same elements)
count() Returns the number of occurrences of the specified element
extend() Add the elements of a list (or any iterable), to the end of the current
list
index() Returns the index of the first occurrence of the specified element
insert() Adds an element at the specified position (without replacement)
pop() Removes the element at the specified position
remove() Removes the first occurrence of the specified element
reverse() Reverses the order of the list
sort() Sorts the list
Python has a set of built-in methods that you can use on lists.
List Methods:
To add an item to the end of the list, use the append() method:
x=['cricket', 'badminton', 'volleyball', 'football']
x.append('PUBG')
print(x)
#Output:
['cricket', 'badminton', 'volleyball', 'football', 'PUBG']
• To insert a list item at a specified index, use the insert() method.
The insert() method inserts an item at the specified index (without replacing)
 Append items:
 Insert items:
x=['cricket', 'badminton', 'volleyball', 'football']
x.insert(2,'PUBG')
print(x)
['cricket', 'badminton', 'PUBG', 'volleyball', 'football']
>>> d1=[23,45,67,3.14]
>>> d1.append(['hi',55])
>>> print (d1)
[23, 45, 67, 3.14, ['hi', 55]]
>>> len(d1)
5
• To append elements from another list to the current list, use
the extend() method. The items will be added at the end of the current list
sport=['cricket', 'badminton', 'volleyball', 'football']
fruits=['apple','cherry']
sport.extend(fruits)
print(sport)
['cricket', 'badminton', 'volleyball', 'football', 'apple', 'cherry']
#Output:
 Extend list:
>>> list1=[1,2,3,4]
>>> list2=['a','b','c','d']
>>> list1.extend(list2)
>>> print(list1)
[1, 2, 3, 4, 'a', 'b', 'c', 'd']
>>> d1=[23,45,67,3.14]
>>>d1.extend( [‘hi’, 55])
>>> print(d1)
[23, 45, 67, 3.14, 'hi', 55]
>>> len(d1)
6
Note: 1) Extend operates on the
existing list taking another list as
argument. So, refers to same
memory
2) Append operates on the existing
list taking a singleton as argument
The extend() method can be used with any iterable object like tuples, sets,
dictionaries etc..
x=['cricket', 'badminton', 'volleyball', 'football'] # list
fruits=('apple','cherry') #tuple
x.extend(fruits)
print(x)
#Output:
['cricket', 'badminton', 'volleyball', 'football', 'apple', 'cherry']
• Remove Specified Item:
The remove() method removes the specified item.
 Add any iterable:
 Remove list items:
x=['cricket', 'badminton', 'volleyball', 'football']
x.remove('badminton')
print(x)
#Output:
['cricket', 'volleyball', 'football']
• Remove w.r.t Index:
The pop() method removes the specified index.
x=['cricket', 'badminton', 'volleyball', 'football']
x.pop(2)
print(x)
#Output:
['cricket', 'badminton', 'football']
Note: If you do not
specify the index,
the pop() method
removes the last item.
>>> list1=['cricket', 'badminton', 'volleyball', 'football', 'hockey']
>>> list1.pop()
'hockey'
>>> print(list1)
['cricket', 'badminton', 'volleyball', 'football']
Note: we can use
negative Indexing also
with pop() method
>>> list1=['cricket', 'badminton', 'volleyball', 'footba
>>> list1.pop(-2)
'hockey'
>>> print(list1)
['cricket', 'badminton', 'football']
• Deleting items:
• The del keyword also removes the specified index:
x=['cricket', 'badminton', 'volleyball', 'football']
del x[1]
print(x)
#Output:
['cricket', 'volleyball', 'football']
• The del keyword can also delete the list completely if index is not specified.
• The clear() method empties the list.
• The list still remains, but it has no content.
• Clear the List:
x=['cricket', 'badminton', 'volleyball', 'football']
x.clear()
print(x)
#Output:
[ ]
>>> list2=['a','b','c','d']
>>> del(list2[1])
>>> print (list2)
['a', 'c', 'd']
>>> list2=['a','b','c','d']
>>> del(list2)
>>> print (list2)
Traceback (most recent call last):
File "<pyshell#50>", line 1, in
<module>
print (list2)
NameError: name 'list2' is not
defined
 Copy Lists:
There are many ways to make a copy, one way is
to use the built-in List method copy().
fruits = ["apple", "banana", "cherry"]
newlist = fruits.copy()
print(newlist)
#Output:
['apple', 'banana', 'cherry']
Another way to make a copy is to use
the built-in method list().
fruits = ["apple", "banana", "cherry"]
newlist = list(fruits)
print(newlist)
#Output:
['apple', 'banana', 'cherry']
A new list can be created with ‘+’ operator
similar to string concatenation.
>>> a=['hi', 'welcome']
>>> b=['to', 'python class']
>>> c=a+b # new list, new memory reference
>>> print ("new list after concatenation is:")
new list after concatenation is:
>>> print (c)
['hi', 'welcome', 'to', 'python class']
 Creating new list using
existing lists (Concatenation)
Note: The * operator produces a new list that “repeats”
the original content
>>> print (a)
['hi', 'welcome']
>>> >>> print (a *3)
['hi', 'welcome', 'hi', 'welcome', 'hi', 'welcome']
 Sort Lists:
• Sort list alphabetically:
List objects have a sort() method that will sort the list alphanumerically, ascending, by default:
['banana', 'kiwi', 'mango', 'orange', 'pineapple']
fruits = ["orange", "mango", "kiwi", "pineapple", "banana"]
fruits.sort()
print(fruits)
#Output:
num = [100, 50, 65, 82, 23]
num.sort()
print(num)
#Output:
• Sort the list numerically:
[23, 50, 65, 82, 100]
• Sort Descending:
• To sort descending, use the keyword argument reverse = True
fruits = ["orange", "mango", "kiwi", "pineapple", "banana"]
fruits.sort(reverse = True)
print(fruits)
#Output:
['pineapple', 'orange', 'mango', 'kiwi', 'banana']
• The reverse() method reverses the current sorting order of the elements.
>>> list1=[23, 'krishna', 'a', 56.44, 'hello']
>>> list1.sort()
Traceback (most recent call last):
File "<pyshell#70>", line 1, in <module>
list1.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
 List operations:
 Concatenation/joining lists
• There are several ways to
join, or concatenate, two or
more lists in Python.
• One of the easiest ways are
by using the + operator.
list1 = ["a", "b", "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
#Output:
['a', 'b', 'c', 1, 2, 3]
list1 = ["a", "b" , "c"]
list2 = [1, 2,3]
for x in list2:
list1.append(x)
print(list1)
#Output:
['a', 'b', 'c', 1, 2, 3]
Another way to
join two lists are
by appending all
the items from
list2 into list1, one
by one:
 We can also use
the extend() method,
whose purpose is to
add elements from one
list to another list
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
#Output:
['a', 'b', 'c', 1, 2, 3]
##list with append method
fruits = ["Apple", "Banana", "Mango"]
# using append() with user input
print(f'Current Fruits List {fruits}')
new = input("Please enter a fruit name:n")
fruits.append(new)
print(f'Updated Fruits List {fruits}')
Output:
Current Fruits List ['Apple', 'Banana', 'Mango']
Please enter a fruit name:
watermelon
Updated Fruits List ['Apple', 'Banana', 'Mango',
'watermelon']
## list with extend method
mylist = [ ] ### empty list
mylist.extend([1, "krishna"]) # extending list elements
print(mylist)
mylist.extend((34.88, True)) # extending tuple elements
print(mylist)
mylist.extend("hello") # extending string elements
print(mylist)
print ("number of elements in the list is:")
print (len(mylist))
Output:
[1, 'krishna']
[1, 'krishna', 34.88, True]
[1, 'krishna', 34.88, True, 'h', 'e', 'l', 'l', 'o']
numberof elements in the list is:
9
 Unpacking lists:
Unpack list and assign them into multiple variables.
numbers=[1,2,3,4,5,6,7,8,9]
first,second,*others,last=numbers
print(first,second)
print(others)
print(last)
#Output:
1 2
[3, 4, 5, 6, 7, 8]
9
NOTE : The number of variables in the left side of the operator must be equal to the number of the list.. If
there are many items in the list we can use *others to pack the rest of the items into the list called other.
Packs the rest of the items.
Unpacks the first and second
item of the list.
Unpacks the last item of the
list.

More Related Content

What's hot

Python Usage (5-minute-summary)
Python Usage (5-minute-summary)Python Usage (5-minute-summary)
Python Usage (5-minute-summary)
Ohgyun Ahn
 
[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4
Kevin Chun-Hsien Hsu
 
Python PCEP Operations On Lists
Python PCEP Operations On ListsPython PCEP Operations On Lists
Python PCEP Operations On Lists
IHTMINSTITUTE
 
1 pythonbasic
1 pythonbasic1 pythonbasic
1 pythonbasic
pramod naik
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About Ruby
Ian Bishop
 
Elixir
ElixirElixir
Clustering com numpy e cython
Clustering com numpy e cythonClustering com numpy e cython
Clustering com numpy e cython
Anderson Dantas
 
Closures
ClosuresClosures
Closures
SV.CO
 
Python an-intro youtube-livestream-day2
Python an-intro youtube-livestream-day2Python an-intro youtube-livestream-day2
Python an-intro youtube-livestream-day2
MAHALAKSHMI P
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
pugpe
 
EuroPython 2015 - Instructions
EuroPython 2015 - InstructionsEuroPython 2015 - Instructions
EuroPython 2015 - Instructions
Max Tepkeev
 
Python collections
Python collectionsPython collections
Python collections
Manusha Dilan
 
Ruby's Arrays and Hashes with examples
Ruby's Arrays and Hashes with examplesRuby's Arrays and Hashes with examples
Ruby's Arrays and Hashes with examples
Niranjan Sarade
 
Open course(programming languages) 20150121
Open course(programming languages) 20150121Open course(programming languages) 20150121
Open course(programming languages) 20150121
JangChulho
 
py_AutoMapMaker
py_AutoMapMakerpy_AutoMapMaker
py_AutoMapMaker
Clint Pearce
 
Basic operations by novi reandy sasmita
Basic operations by novi reandy sasmitaBasic operations by novi reandy sasmita
Basic operations by novi reandy sasmita
beasiswa
 

What's hot (16)

Python Usage (5-minute-summary)
Python Usage (5-minute-summary)Python Usage (5-minute-summary)
Python Usage (5-minute-summary)
 
[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4
 
Python PCEP Operations On Lists
Python PCEP Operations On ListsPython PCEP Operations On Lists
Python PCEP Operations On Lists
 
1 pythonbasic
1 pythonbasic1 pythonbasic
1 pythonbasic
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About Ruby
 
Elixir
ElixirElixir
Elixir
 
Clustering com numpy e cython
Clustering com numpy e cythonClustering com numpy e cython
Clustering com numpy e cython
 
Closures
ClosuresClosures
Closures
 
Python an-intro youtube-livestream-day2
Python an-intro youtube-livestream-day2Python an-intro youtube-livestream-day2
Python an-intro youtube-livestream-day2
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
 
EuroPython 2015 - Instructions
EuroPython 2015 - InstructionsEuroPython 2015 - Instructions
EuroPython 2015 - Instructions
 
Python collections
Python collectionsPython collections
Python collections
 
Ruby's Arrays and Hashes with examples
Ruby's Arrays and Hashes with examplesRuby's Arrays and Hashes with examples
Ruby's Arrays and Hashes with examples
 
Open course(programming languages) 20150121
Open course(programming languages) 20150121Open course(programming languages) 20150121
Open course(programming languages) 20150121
 
py_AutoMapMaker
py_AutoMapMakerpy_AutoMapMaker
py_AutoMapMaker
 
Basic operations by novi reandy sasmita
Basic operations by novi reandy sasmitaBasic operations by novi reandy sasmita
Basic operations by novi reandy sasmita
 

Similar to Python lists

python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
AshaWankar1
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
Pytho lists
Pytho listsPytho lists
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
MihirDatir1
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
Asst.prof M.Gokilavani
 
Python data structures
Python data structuresPython data structures
Python data structures
Tony Nguyen
 
Python data structures
Python data structuresPython data structures
Python data structures
Luis Goldster
 
Python data structures
Python data structuresPython data structures
Python data structures
James Wong
 
Python data structures
Python data structuresPython data structures
Python data structures
Young Alista
 
Python data structures
Python data structuresPython data structures
Python data structures
Fraboni Ec
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
Yagna15
 
Python Lecture 8
Python Lecture 8Python Lecture 8
Python Lecture 8
Inzamam Baig
 
Farhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionariesFarhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionaries
Farhana Shaikh
 
Python lecture 04
Python lecture 04Python lecture 04
Python lecture 04
Tanwir Zaman
 
XI_CS_Notes for strings.docx
XI_CS_Notes for strings.docxXI_CS_Notes for strings.docx
XI_CS_Notes for strings.docx
AnithaSathiaseelan1
 
beginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptxbeginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptx
HongAnhNguyn285885
 
Python lists &amp; sets
Python lists &amp; setsPython lists &amp; sets
Python lists &amp; sets
Aswini Dharmaraj
 
Session -5for students.pdf
Session -5for students.pdfSession -5for students.pdf
Session -5for students.pdf
priyanshusoni53
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
Paige Bailey
 
Python elements list you can study .pdf
Python elements list you can study  .pdfPython elements list you can study  .pdf
Python elements list you can study .pdf
AUNGHTET61
 

Similar to Python lists (20)

python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Pytho lists
Pytho listsPytho lists
Pytho lists
 
Pythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptxPythonlearn-08-Lists.pptx
Pythonlearn-08-Lists.pptx
 
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdfGE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
 
Python data structures
Python data structuresPython data structures
Python data structures
 
Python data structures
Python data structuresPython data structures
Python data structures
 
Python data structures
Python data structuresPython data structures
Python data structures
 
Python data structures
Python data structuresPython data structures
Python data structures
 
Python data structures
Python data structuresPython data structures
Python data structures
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
 
Python Lecture 8
Python Lecture 8Python Lecture 8
Python Lecture 8
 
Farhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionariesFarhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionaries
 
Python lecture 04
Python lecture 04Python lecture 04
Python lecture 04
 
XI_CS_Notes for strings.docx
XI_CS_Notes for strings.docxXI_CS_Notes for strings.docx
XI_CS_Notes for strings.docx
 
beginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptxbeginners_python_cheat_sheet_pcc_all (3).pptx
beginners_python_cheat_sheet_pcc_all (3).pptx
 
Python lists &amp; sets
Python lists &amp; setsPython lists &amp; sets
Python lists &amp; sets
 
Session -5for students.pdf
Session -5for students.pdfSession -5for students.pdf
Session -5for students.pdf
 
Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!Python 101++: Let's Get Down to Business!
Python 101++: Let's Get Down to Business!
 
Python elements list you can study .pdf
Python elements list you can study  .pdfPython elements list you can study  .pdf
Python elements list you can study .pdf
 

More from Krishna Nanda

Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
Krishna Nanda
 
Python dictionaries
Python dictionariesPython dictionaries
Python dictionaries
Krishna Nanda
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
Krishna Nanda
 
Python- strings
Python- stringsPython- strings
Python- strings
Krishna Nanda
 
Python-files
Python-filesPython-files
Python-files
Krishna Nanda
 
Computer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layerComputer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layer
Krishna Nanda
 
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLSComputer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
Krishna Nanda
 
COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4
Krishna Nanda
 
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
Krishna Nanda
 
Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1
Krishna Nanda
 
Computer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LANComputer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LAN
Krishna Nanda
 
Computer Communication Networks-Network Layer
Computer Communication Networks-Network LayerComputer Communication Networks-Network Layer
Computer Communication Networks-Network Layer
Krishna Nanda
 
Lk module3
Lk module3Lk module3
Lk module3
Krishna Nanda
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
Krishna Nanda
 
Lk module4 file
Lk module4 fileLk module4 file
Lk module4 file
Krishna Nanda
 
Lk module5 pointers
Lk module5 pointersLk module5 pointers
Lk module5 pointers
Krishna Nanda
 

More from Krishna Nanda (16)

Python regular expressions
Python regular expressionsPython regular expressions
Python regular expressions
 
Python dictionaries
Python dictionariesPython dictionaries
Python dictionaries
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
 
Python- strings
Python- stringsPython- strings
Python- strings
 
Python-files
Python-filesPython-files
Python-files
 
Computer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layerComputer Communication Networks- Introduction to Transport layer
Computer Communication Networks- Introduction to Transport layer
 
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLSComputer Communication Networks- TRANSPORT LAYER PROTOCOLS
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
 
COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS -IPv4
 
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
 
Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Routing protocols 1
 
Computer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LANComputer Communication Networks-Wireless LAN
Computer Communication Networks-Wireless LAN
 
Computer Communication Networks-Network Layer
Computer Communication Networks-Network LayerComputer Communication Networks-Network Layer
Computer Communication Networks-Network Layer
 
Lk module3
Lk module3Lk module3
Lk module3
 
Lk module4 structures
Lk module4 structuresLk module4 structures
Lk module4 structures
 
Lk module4 file
Lk module4 fileLk module4 file
Lk module4 file
 
Lk module5 pointers
Lk module5 pointersLk module5 pointers
Lk module5 pointers
 

Recently uploaded

Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
Dr Ramhari Poudyal
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
Las Vegas Warehouse
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
gerogepatton
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
Rahul
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
ihlasbinance2003
 
Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
zubairahmad848137
 
Textile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdfTextile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdf
NazakatAliKhoso2
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
MIGUELANGEL966976
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
Recycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part IIRecycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part II
Aditya Rajan Patra
 
Heat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation pptHeat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation ppt
mamunhossenbd75
 
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
University of Maribor
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball playEric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
enizeyimana36
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
Yasser Mahgoub
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 

Recently uploaded (20)

Literature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptxLiterature Review Basics and Understanding Reference Management.pptx
Literature Review Basics and Understanding Reference Management.pptx
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
 
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
5214-1693458878915-Unit 6 2023 to 2024 academic year assignment (AutoRecovere...
 
Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
 
Textile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdfTextile Chemical Processing and Dyeing.pdf
Textile Chemical Processing and Dyeing.pdf
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdfBPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
BPV-GUI-01-Guide-for-ASME-Review-Teams-(General)-10-10-2023.pdf
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
Recycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part IIRecycled Concrete Aggregate in Construction Part II
Recycled Concrete Aggregate in Construction Part II
 
Heat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation pptHeat Resistant Concrete Presentation ppt
Heat Resistant Concrete Presentation ppt
 
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball playEric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
Eric Nizeyimana's document 2006 from gicumbi to ttc nyamata handball play
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
2008 BUILDING CONSTRUCTION Illustrated - Ching Chapter 02 The Building.pdf
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 

Python lists

  • 1. Module3 LISTS Prof. Krishnananda L Department of ECE Govt SKSJTI Bengaluru
  • 2. Contents: Introduction Features The list constructor ( ): List slicing Replace list items Check if item exists in a list Loop list List comprehension Built-in function List methods List operation Unpacking list.
  • 3. PYTHON DATA TYPES Python supports 3 sequence data types: 1. LISTS 2. TUPLES 3. STRINGS Other two important data structures in Python are: 1. SET 2. DICTIONARY
  • 4. List is a collection which is ordered , mutable and indexed Lists are created by square brackets and the elements in the list are separated by commas. Lists are used to store multiple items in a single entity. Lists allow duplicates LIST: # exampleof lists >>>games=['cricket','badminton','volleyball'] >>>print (games) ['cricket', 'badminton','volleyball'] >>>List=[1,2,,3,4,] >>>print(List) [1, 2, 3, 4]
  • 5. List items are ordered means, items can be accessed using positional index. In general, new items will be placed at the end of the list. #Lists allow duplicate values: >>>games=['cricket','badminton','volleyball','cricket','volleyball'] >>>print(games) #output ['cricket','badminton', 'volleyball', 'cricket', 'volleyball'] >>> len(games) 5 Lists are mutablemeans we can change, add and remove items in a list after it has been created. Since the list is indexed , lists can have items with same value. Ordered: Mutable: Allows duplicate:
  • 6. 1. List can contain elements of different data types i.e., string , int, Boolean, tuple etc. Lists are Mutable Features: >>>list=['cricket','abc',42,29, 0, True] >>>print(list) #output ['cricket','abc', 42,29, 0, True] >>>list=['cricket','abc',42,29.0,True] >>>print(type(list)) #output <class 'list'> >>> list =[23, 45, 'krishna', (34,56)] >>> print (list) [23, 45, 'krishna', (34, 56)] 2. Lists are defined as objects with the data type ‘list’. >>> list[1]='hello‘ ## mutability >>> print (list) ## same memory reference [23, 'hello', 'krishna', (34, 56)] >>> list[3]=(89,'welcome')#mutability >>> print (list) [23, 'hello', 'krishna', (89, 'welcome')] >>>len(list) >>> list =[23, 45, 'krishna', (34,56)] >>> print (list[2])# accessing list element krishna
  • 8. The list constructor ( ) : It is also possible to use the list ( ) constructor when creating a new list. x=list(('cricket','abc',42,29.0,True)) """note the double round-brackets""" print(x) #output: ['cricket','abc', 42,29.0, True] Simple Operations on Lists >> list1=[23, 55,77] >>> list2=[23, 55, 77] >>> list1==list2 True >>> list1 is list2 False >>> list2=list1 >>> list2 is list1 True >>> d1=['a','b','c'] >>> d2=['a','b','d'] >>> d1<d2 True >>> min(d1) 'a' >>> max(d2) 'd‘ >>> sum(list1) >>> list1=[20, 'hi', 40] >>> list2=[20, 40, 'hi'] >>> list1==list2 False >>> list1>list2 Traceback (most recent call last): File "<pyshell#16>", line 1, in <module> list1>list2 TypeError: '>' not supported between instances of 'str' and 'int' >>> ["abc"]>["bac"] False >>> [45, 67, 89] + ['hi', 'hello'] [45, 67, 89, 'hi', 'hello']
  • 9. Assignment and References >>>x = 3 • First, an integer 3 is created and stored in memory • A name x is created • A reference to the memory location storing 3 is then assigned to the name x • So: When we say that the value of x is 3, we mean that x now refers to the integer 3 Ex with immutable data like integers: >>> x=10 # Creates 10, name x refers to 10 >>> y=x # Creates name y, refers to 10. >>> id(x) 1400633408 >>> id(y) # x and y refer to same location 1400633408 >>> print(y) 10 >>> y=20 ## creates reference for 20 >>> id(y) ### changes y 1400633568 ## y points to a new mem location >>> print (y) 20 >>> print(x) # no effect on x. Refers to 10 10 Note: Binding a variable in Python means setting a name to hold a reference to some object. • Assignment creates references, not copies  x = y does not make a copy of the object y references  x = y makes x reference the object y references
  • 10. List Assignment >>> d=[1,2,3,4] ## d references the list [1,2,3,4] >>> id (d) 56132040 >>> b=d ## b now references what d references >>> id(b) 56132040 >>> b[3]=10 ## changes the list which b references >>> print (b) [1, 2, 3, 10] >>> print (d) ### change reflected in original also [1, 2, 3, 10] >>>a=[23, 45, 'hi'] >>> b=a # two names refer to same memory >>> id(a) 24931464 >>> id(b) 24931464 ## only one list. Two names refer to it >>> a.append('welcome') ## change list element >>> id(a) 24931464 # refer to same object >>> print (a) [23, 45, 'hi', 'welcome'] >>> print (b) ## Change in one name affects the other [23, 45, 'hi', 'welcome'] Lists are “mutable.” When we change the values of list elements, we do it in place. We don’t copy them into a new memory address each time. If we type y=x and then modify y, both x and y are changed Note: b=a[:] creates copy of list a. Now we have two independent copies and two references
  • 11. List Slicing: x=list(('cricket','abc',42,29.0,True)) print(x[-1]) print(x[2]) print(x[0]) #Output: True 42 cricket Positive indexing 0 1 2 3 4 List Cricket abc 42 29.0 True Negative indexing -5 -4 -3 -2 -1 Note: Slicingis helpful to get a subset of the original list
  • 12.  Range of positive indexes: We can specify a range of indexes by specifying where to start and where to end the range. # RETURN THE THIRD ,FOURTH AND FIFTH TERM: >>>x=['cricket','badminton','volleyball','football','hockey','cheese'] print(x[2:5]) #output: ['volleyball', 'football', 'hockey'] 2 3 4 Index number NOTE: 1) The search will start at Index 2 ( included) and end at index 5 (not included). 2)Remember that the first item has index 0. 3)The index ranges from 0 to (n-1).
  • 13. By leaving out the start value, by default the range will start at the first item. x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle'] print(x[:4]) #output: [‘cricket’,’badminton’,’volleyball', 'football'] By leaving out the end value, by default the range will go on to the end of the list. x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle'] print(x[2:]) #output: ['volleyball', 'football', 'hockey', 'shuttle'] Herehockeyhasa index value 4 and isexcluded becausetherange isfrom0:(n-1) 0:(4-1) i.e.,0:3 Herevolleyball hasa index value 2 andis included becausethe range isfrom 2: last itemin thelist
  • 14. If you want to search the item from the end of the list , negative indexes can be used. >>>x=['cricket', 'badminton', 'volleyball', 'football','hockey', 'shuttle'] print(x[-3:-1]) #output: ['football', 'hockey'] -6 -5 -4 -3 -2 -1 Here the range is from -3(included) : -1(excluded). Shuttle is excluded because of the range of index(-1).  Range of negative indexes:
  • 15. To replace the value of a specific item ,refer to the index number.  Replace/Modify items in a List #CHANGE THE SECOND ITEM IN A LIST: x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle'] x[2]='PUBG‘ print(x) #output: ['cricket', 'badminton', 'PUBG', 'football', 'hockey', 'shuttle'] Here volleyballis replacedbyPUBG • Replace a range of elements To replace the value of items within a specific range, define a list with the new values, and refer to the range of index numbers where you want to insert the new values.
  • 16. x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle'] x[4:]='PUBG','FREEFIRE’ print(x) #Output: ['cricket', 'badminton', 'volleyball', 'football', 'PUBG', 'FREEFIRE'] We can also replace this line by x[4:6]=[‘PUBG,’FREEFIRE’] If you insert more items than you replace , the new items will be inserted where you specified, and the remaining itemsmove accordingly. >>>x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle'] >>>len(x) 6 >>>x[2:3]='PUBG','FREEFIRE’ >>>print (x) >>>len(x) 7 ['cricket', 'badminton', 'PUBG', 'FREEFIRE', 'football', 'hockey', 'shuttle']
  • 17. If you insert less items than you replace , the new items will be inserted where you specified, and theremaining items move accordingly. >>>x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle'] >>>x[2:4]=['PUBG'] print(x) #Output: ['cricket', 'badminton', 'PUBG', 'hockey', 'shuttle'] Note: If the range of index which must be replaced is not equal to the item to be replaced, the extra mentioned range of item is removed from the list … i.e., in the range x[2:4] we can replace 2 items but we replaced only 1 item PUBG, hence football is removedin the list. Here square brackets are must and necessary. If not used the single item PUBG is BY DEFAULT taken as 4 individual item as ‘P’,’U’ ,’B’,’G’. >>> list=[] #emptylist >>> len (list) 0 >>> type(list) >>> list=[34 ] # list with single element >>> len (list) 1 >>> type(list) <class 'list'>
  • 18. x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle'] x[2:4]='PUBG' print(x) #Output: ['cricket', 'badminton', 'P','U', 'B', 'G', 'hockey', 'shuttle'] Here squarebrackets are notusedhence the single item PUBG is BY DEFAULTtakenas 4 individualitemas‘P’,’U’ ,’B’,’G’. NOTE : The length of the list will change when the number of items inserteddoes not match thenumber of itemsreplaced.  Check if item exists in a list: To determine if a specified item is present in a list use the in keyword. x=['cricket', 'badminton', 'volleyball', 'football','hockey','shuttle'] if 'volleyball' in x: print(“yes, ‘volleyball’ is in the list x”) #output: yes ‘volleyball’ is in the list x
  • 19. List Comparison, use of is, in operator >>> l1=[1,2,3,4] >>> l2=[1,2,3,4] >>> l3=[1,3,2,4] >>> l1==l2 True >>> l1==l3 False >>> id(l1) 1788774040000 >>> id(l2) 1788777176704 >>> id(l3) 1788777181312 >>> l1 is l2 False >>>> l1=['a','b','c','d'] >>> l2=['a','b','c','d'] >>> l1 is l2 False >>> l1==l2 True >>> if 'a' in l1: print (" 'a' is present") 'a' is present >>> if 'u' not in l1: print (" 'u' is not present") 'u' is not present
  • 20. Loop Through a List You can loop through the list items by using a for loop: Loop list: fruits=['apple','cherry','grapes'] for x in fruits: print(x) #Output: apple cherry grapes  Loop Through the Index Numbers • You can also loop through the list items by referring to their index number. • Use the range() and len() functions to create a suitable iterable. fruits= ["apple", "banana", "cherry"] for i in range(len(fruits)): print(fruits[i]) #Output: apple banana cherry
  • 21.  Using a While Loop: • You can loop through the list items by using a while loop. • Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. • Update the index by 1 after each iteration. thislist = ["apple", "banana", "cherry"] i = 0 while i < len(thislist): print(thislist[i]) i = i + 1 #Output: apple banana cherry thislist = ["apple", "banana", "cherry"] [print(x) for x in thislist] #Output: apple banana cherry  Looping Using List Comprehension: List Comprehension offers the shortest syntax for looping through lists:
  • 22. List Comprehension: List comprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. Example: • Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name. ['apple', 'banana', 'mango'] fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [ ] for x in fruits: if "a" in x: newlist.append(x) print(newlist) #Output: • Without list comprehension you will have to write a for statement with a conditional test inside: This line specifies that the newlist must appendonlythe fruits whichcontains the letter‘a’ in them.
  • 23. • With list comprehension one line of code is enough to create a new list: fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [x for x in fruitsif "a" in x] print(newlist) #Output: ['apple', 'banana', 'mango'] • The Syntax: newlist = [expression for item in iterable if condition == True] • Condition: The condition is like a filter that only accepts the items that evaluates to True. fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [x for x in fruits if x != "apple"] print(newlist) #Output: ['banana', 'cherry', 'kiwi', 'mango'] The condition if x!= "apple" will return True for all elements other than "apple", making the new list contain all fruits except "apple". Note: The iterable can be any iterable object, like a list, tuple, set etc. Note: The expression is the current item in the iteration, but it is also the outcome, which you can manipulate before it ends up like a list item in the new list
  • 24. Some examples of List Comprehension >>> newlist = [x for x in range(10)] >>> print (newlist) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]: >>> newlist = [x for x in range(10) if x < 5] >>> print (newlist) [0, 1, 2, 3, 4] >>> list1=['cricket','badminton', 'volleyball', 'football','hockey'] >>> newlist = [x.upper() for x in list1] >>> print (newlist) ['CRICKET', 'BADMINTON', 'VOLLEYBALL', 'FOOTBALL', 'HOCKEY'] >>> newlist1 = ['welcome' for x in list1] >>> print (newlist1) ['welcome', 'welcome', 'welcome', 'welcome', 'welcome']
  • 25. Method Description append() Adds an element at the end of the list clear() Removes all the elements from the list copy() Returns a copy of the list (creates a new list with same elements) count() Returns the number of occurrences of the specified element extend() Add the elements of a list (or any iterable), to the end of the current list index() Returns the index of the first occurrence of the specified element insert() Adds an element at the specified position (without replacement) pop() Removes the element at the specified position remove() Removes the first occurrence of the specified element reverse() Reverses the order of the list sort() Sorts the list Python has a set of built-in methods that you can use on lists. List Methods:
  • 26. To add an item to the end of the list, use the append() method: x=['cricket', 'badminton', 'volleyball', 'football'] x.append('PUBG') print(x) #Output: ['cricket', 'badminton', 'volleyball', 'football', 'PUBG'] • To insert a list item at a specified index, use the insert() method. The insert() method inserts an item at the specified index (without replacing)  Append items:  Insert items: x=['cricket', 'badminton', 'volleyball', 'football'] x.insert(2,'PUBG') print(x) ['cricket', 'badminton', 'PUBG', 'volleyball', 'football'] >>> d1=[23,45,67,3.14] >>> d1.append(['hi',55]) >>> print (d1) [23, 45, 67, 3.14, ['hi', 55]] >>> len(d1) 5
  • 27. • To append elements from another list to the current list, use the extend() method. The items will be added at the end of the current list sport=['cricket', 'badminton', 'volleyball', 'football'] fruits=['apple','cherry'] sport.extend(fruits) print(sport) ['cricket', 'badminton', 'volleyball', 'football', 'apple', 'cherry'] #Output:  Extend list: >>> list1=[1,2,3,4] >>> list2=['a','b','c','d'] >>> list1.extend(list2) >>> print(list1) [1, 2, 3, 4, 'a', 'b', 'c', 'd'] >>> d1=[23,45,67,3.14] >>>d1.extend( [‘hi’, 55]) >>> print(d1) [23, 45, 67, 3.14, 'hi', 55] >>> len(d1) 6 Note: 1) Extend operates on the existing list taking another list as argument. So, refers to same memory 2) Append operates on the existing list taking a singleton as argument
  • 28. The extend() method can be used with any iterable object like tuples, sets, dictionaries etc.. x=['cricket', 'badminton', 'volleyball', 'football'] # list fruits=('apple','cherry') #tuple x.extend(fruits) print(x) #Output: ['cricket', 'badminton', 'volleyball', 'football', 'apple', 'cherry'] • Remove Specified Item: The remove() method removes the specified item.  Add any iterable:  Remove list items:
  • 29. x=['cricket', 'badminton', 'volleyball', 'football'] x.remove('badminton') print(x) #Output: ['cricket', 'volleyball', 'football'] • Remove w.r.t Index: The pop() method removes the specified index. x=['cricket', 'badminton', 'volleyball', 'football'] x.pop(2) print(x) #Output: ['cricket', 'badminton', 'football'] Note: If you do not specify the index, the pop() method removes the last item. >>> list1=['cricket', 'badminton', 'volleyball', 'football', 'hockey'] >>> list1.pop() 'hockey' >>> print(list1) ['cricket', 'badminton', 'volleyball', 'football'] Note: we can use negative Indexing also with pop() method >>> list1=['cricket', 'badminton', 'volleyball', 'footba >>> list1.pop(-2) 'hockey' >>> print(list1) ['cricket', 'badminton', 'football']
  • 30. • Deleting items: • The del keyword also removes the specified index: x=['cricket', 'badminton', 'volleyball', 'football'] del x[1] print(x) #Output: ['cricket', 'volleyball', 'football'] • The del keyword can also delete the list completely if index is not specified. • The clear() method empties the list. • The list still remains, but it has no content. • Clear the List: x=['cricket', 'badminton', 'volleyball', 'football'] x.clear() print(x) #Output: [ ] >>> list2=['a','b','c','d'] >>> del(list2[1]) >>> print (list2) ['a', 'c', 'd'] >>> list2=['a','b','c','d'] >>> del(list2) >>> print (list2) Traceback (most recent call last): File "<pyshell#50>", line 1, in <module> print (list2) NameError: name 'list2' is not defined
  • 31.  Copy Lists: There are many ways to make a copy, one way is to use the built-in List method copy(). fruits = ["apple", "banana", "cherry"] newlist = fruits.copy() print(newlist) #Output: ['apple', 'banana', 'cherry'] Another way to make a copy is to use the built-in method list(). fruits = ["apple", "banana", "cherry"] newlist = list(fruits) print(newlist) #Output: ['apple', 'banana', 'cherry'] A new list can be created with ‘+’ operator similar to string concatenation. >>> a=['hi', 'welcome'] >>> b=['to', 'python class'] >>> c=a+b # new list, new memory reference >>> print ("new list after concatenation is:") new list after concatenation is: >>> print (c) ['hi', 'welcome', 'to', 'python class']  Creating new list using existing lists (Concatenation) Note: The * operator produces a new list that “repeats” the original content >>> print (a) ['hi', 'welcome'] >>> >>> print (a *3) ['hi', 'welcome', 'hi', 'welcome', 'hi', 'welcome']
  • 32.  Sort Lists: • Sort list alphabetically: List objects have a sort() method that will sort the list alphanumerically, ascending, by default: ['banana', 'kiwi', 'mango', 'orange', 'pineapple'] fruits = ["orange", "mango", "kiwi", "pineapple", "banana"] fruits.sort() print(fruits) #Output: num = [100, 50, 65, 82, 23] num.sort() print(num) #Output: • Sort the list numerically: [23, 50, 65, 82, 100]
  • 33. • Sort Descending: • To sort descending, use the keyword argument reverse = True fruits = ["orange", "mango", "kiwi", "pineapple", "banana"] fruits.sort(reverse = True) print(fruits) #Output: ['pineapple', 'orange', 'mango', 'kiwi', 'banana'] • The reverse() method reverses the current sorting order of the elements. >>> list1=[23, 'krishna', 'a', 56.44, 'hello'] >>> list1.sort() Traceback (most recent call last): File "<pyshell#70>", line 1, in <module> list1.sort() TypeError: '<' not supported between instances of 'str' and 'int'
  • 34.  List operations:  Concatenation/joining lists • There are several ways to join, or concatenate, two or more lists in Python. • One of the easiest ways are by using the + operator. list1 = ["a", "b", "c"] list2 = [1, 2, 3] list3 = list1 + list2 print(list3) #Output: ['a', 'b', 'c', 1, 2, 3] list1 = ["a", "b" , "c"] list2 = [1, 2,3] for x in list2: list1.append(x) print(list1) #Output: ['a', 'b', 'c', 1, 2, 3] Another way to join two lists are by appending all the items from list2 into list1, one by one:  We can also use the extend() method, whose purpose is to add elements from one list to another list list1 = ["a", "b" , "c"] list2 = [1, 2, 3] list1.extend(list2) print(list1) #Output: ['a', 'b', 'c', 1, 2, 3]
  • 35. ##list with append method fruits = ["Apple", "Banana", "Mango"] # using append() with user input print(f'Current Fruits List {fruits}') new = input("Please enter a fruit name:n") fruits.append(new) print(f'Updated Fruits List {fruits}') Output: Current Fruits List ['Apple', 'Banana', 'Mango'] Please enter a fruit name: watermelon Updated Fruits List ['Apple', 'Banana', 'Mango', 'watermelon'] ## list with extend method mylist = [ ] ### empty list mylist.extend([1, "krishna"]) # extending list elements print(mylist) mylist.extend((34.88, True)) # extending tuple elements print(mylist) mylist.extend("hello") # extending string elements print(mylist) print ("number of elements in the list is:") print (len(mylist)) Output: [1, 'krishna'] [1, 'krishna', 34.88, True] [1, 'krishna', 34.88, True, 'h', 'e', 'l', 'l', 'o'] numberof elements in the list is: 9
  • 36.  Unpacking lists: Unpack list and assign them into multiple variables. numbers=[1,2,3,4,5,6,7,8,9] first,second,*others,last=numbers print(first,second) print(others) print(last) #Output: 1 2 [3, 4, 5, 6, 7, 8] 9 NOTE : The number of variables in the left side of the operator must be equal to the number of the list.. If there are many items in the list we can use *others to pack the rest of the items into the list called other. Packs the rest of the items. Unpacks the first and second item of the list. Unpacks the last item of the list.