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

PPTX
Python data structures
PDF
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
PPT
Ken20150417
PDF
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of Wrangling
PDF
Bash Learning By Examples
KEY
Ruby nooks & crannies
PDF
Elixir & Phoenix – fast, concurrent and explicit
PDF
Elixir & Phoenix – fast, concurrent and explicit
Python data structures
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Ken20150417
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of Wrangling
Bash Learning By Examples
Ruby nooks & crannies
Elixir & Phoenix – fast, concurrent and explicit
Elixir & Phoenix – fast, concurrent and explicit

What's hot (16)

PDF
Python Usage (5-minute-summary)
PDF
[1062BPY12001] Data analysis with R / week 4
PPTX
Python PCEP Operations On Lists
PDF
1 pythonbasic
PDF
Let’s Talk About Ruby
PDF
PDF
Clustering com numpy e cython
PDF
Closures
PDF
Python an-intro youtube-livestream-day2
PDF
Palestra sobre Collections com Python
PPTX
EuroPython 2015 - Instructions
PDF
Python collections
PPTX
Ruby's Arrays and Hashes with examples
PPTX
Open course(programming languages) 20150121
RTF
py_AutoMapMaker
PDF
Basic operations by novi reandy sasmita
Python Usage (5-minute-summary)
[1062BPY12001] Data analysis with R / week 4
Python PCEP Operations On Lists
1 pythonbasic
Let’s Talk About Ruby
Clustering com numpy e cython
Closures
Python an-intro youtube-livestream-day2
Palestra sobre Collections com Python
EuroPython 2015 - Instructions
Python collections
Ruby's Arrays and Hashes with examples
Open course(programming languages) 20150121
py_AutoMapMaker
Basic operations by novi reandy sasmita
Ad

Similar to Python lists (20)

PDF
python_avw - Unit-03.pdf
PPTX
Datastructures in python
PPTX
Pythonlearn-08-Lists.pptx
PPTX
Unit 4.pptx python list tuples dictionary
PDF
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
PPTX
Python data structures
PPTX
Python data structures
PPTX
Python data structures
PPTX
Python data structures
PPTX
Python data structures
PPTX
institute of techonolgy and education tr
PPTX
Lists.pptx
PPTX
Python Lecture 8
PPTX
Pythonlearn-08-Lists (1).pptxaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...
PPTX
Farhana shaikh webinar_dictionaries
PDF
Python lecture 04
DOCX
XI_CS_Notes for strings.docx
PPTX
beginners_python_cheat_sheet_pcc_all (3).pptx
PDF
Python lists &amp; sets
python_avw - Unit-03.pdf
Datastructures in python
Pythonlearn-08-Lists.pptx
Unit 4.pptx python list tuples dictionary
GE3151 PSPP UNIT IV QUESTION BANK.docx.pdf
Python data structures
Python data structures
Python data structures
Python data structures
Python data structures
institute of techonolgy and education tr
Lists.pptx
Python Lecture 8
Pythonlearn-08-Lists (1).pptxaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...
Farhana shaikh webinar_dictionaries
Python lecture 04
XI_CS_Notes for strings.docx
beginners_python_cheat_sheet_pcc_all (3).pptx
Python lists &amp; sets
Ad

More from Krishna Nanda (16)

PDF
Python regular expressions
PDF
Python dictionaries
PDF
Python-Tuples
PDF
Python- strings
PDF
Python-files
PDF
Computer Communication Networks- Introduction to Transport layer
PDF
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
PDF
COMPUTER COMMUNICATION NETWORKS -IPv4
PDF
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
PDF
Computer Communication Networks-Routing protocols 1
PDF
Computer Communication Networks-Wireless LAN
PDF
Computer Communication Networks-Network Layer
PDF
Lk module3
PDF
Lk module4 structures
PDF
Lk module4 file
PDF
Lk module5 pointers
Python regular expressions
Python dictionaries
Python-Tuples
Python- strings
Python-files
Computer Communication Networks- Introduction to Transport layer
Computer Communication Networks- TRANSPORT LAYER PROTOCOLS
COMPUTER COMMUNICATION NETWORKS -IPv4
COMPUTER COMMUNICATION NETWORKS-R-Routing protocols 2
Computer Communication Networks-Routing protocols 1
Computer Communication Networks-Wireless LAN
Computer Communication Networks-Network Layer
Lk module3
Lk module4 structures
Lk module4 file
Lk module5 pointers

Recently uploaded (20)

PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPT
Project quality management in manufacturing
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PDF
Well-logging-methods_new................
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
CH1 Production IntroductoryConcepts.pptx
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
Lecture Notes Electrical Wiring System Components
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
IOT PPTs Week 10 Lecture Material.pptx of NPTEL Smart Cities contd
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
Project quality management in manufacturing
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
Well-logging-methods_new................
CYBER-CRIMES AND SECURITY A guide to understanding
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
OOP with Java - Java Introduction (Basics)
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Internet of Things (IOT) - A guide to understanding
CH1 Production IntroductoryConcepts.pptx
Automation-in-Manufacturing-Chapter-Introduction.pdf
Lecture Notes Electrical Wiring System Components
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Mitigating Risks through Effective Management for Enhancing Organizational Pe...

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.