List in
Python
List Creation
List
• In python, a list inPython
can be defined as a collection of
values or items.
• The items in the list are separated with the comma
(,) and
Syntax: with the square brackets [ ].
enclosed
list-var=
[ value1,value2,value3,…. ]
Example: “listdemo.py
L1 = [] ” Output: python
L2 = [123,"python", 3.7] listdemo.py
L3 = [1, 2, 3, 4, 5, 6] []
L4=["C","Java","Python"] [123, 'python',
print(L1) 3.7] [1, 2, 3, 4,
print(L2) 5, 6]
print(L3) ['C','Java','Python
print(L4) ']
List Indexing
List Indexing
• Like stringinPython
sequence, the indexing of the python
lists starts from 0, i.e. the first element of the list is
stored at the 0th index, the second element of the
list
•The is elements
stored at of
the 1stlist
the index, and
can be so on. by
accessed
operator
using
[]. the slice
Exampl
mylist=[‘banana’,’apple’,’mango’,’tomat
e: o’,’berry’]
• mylist[0]=”ban mylist[1:3]=[”apple”,”m
• mylist[2]=”ma
ana” ango”]
ngo”
List Indexing cont
inPython …
• Unlike other languages, python provides us the
flexibility to use the negative indexing also. The
negative indices are counted from the right.
• The last element (right most) of the list has the
index -1, its
adjacent left element is present at the index -2 and so
on until
Example:
the left most element is encountered.
mylist=[‘banana’,’apple’,’mango’,’tomato’,’berry
’]
• mylist[- mylist[-4:-
• 1]=”berry” 2]=[“apple”,mango”]
List Operators
List Operators
inPython
It is known as concatenation operator used to
+ concatenate two lists.
It is known as repetition operator. It concatenates
*
the multiple
copies of the same list.
[
It is known as slice operator. It is used to access the
]
[:
list item
from list.
]
i
It is known as range slice operator. It is used to
n
not access the range
of list items from list.
in
It is known as membership operator. It returns if a
List Operators cont
…
inPython
Example:“listopdemo.py”
num=[1,2,3,4,5]
lang=['python','c','java','php’]
print(num + lang) #concatenates two lists
print(num * 2) #concatenates same list 2 times
print(lang[2]) # prints 2nd index value
print(lang[1:4]) #prints values from 1st to 3rd
index. print('cpp' in lang) # prints False
print(6 not in num) # prints True
Output: pythonlistopdemo.p
y
[1,2,3,4,5,'python','c','java','php']
[1,2,3,4,5,1,2,3,4,5]
Java
['c','java','php’]
False
True
How to update or change elements to
• a list?
Python allows us to modify the list items by using
the slice and assignment operator.
•
We can use assignment operator ( = ) to change an
item or a
Example:
“listopdemo1.py”
range of items.
num=[1,2,3,4,5] Output: python
print(num) num[2]=30 listopdemo1.py
print(num) [1, 2, 3, 4, 5]
num[1:3]=[25,36] [1, 2, 30, 4, 5]
print(num) [1, 25, 36, 4, 5]
num[4]="Python" [1, 25, 36, 4,
print(num) 'Python']
How to delete or remove elements
• from a allows
Python list? us to delete one or more items in a
list by using the del keyword.
Example:
“listopdemo2.py”
num=[1,2,3,4,5]
print(num)
del num[1]
print(num)
del num[1:3]
print(num)
Output:
pythonlistopdemo2.p
y
[1,2, 3, 4, 5]
[1,3, 4, 5]
[1,5]
Iterating a
• List by using a for - in loop. A
A list can be iterated
simple list containing four strings can be iterated as
follows..
Example: “listopdemo3.py”
lang=['python','c','java','ph
p‘] print("The list items are
\n")
for in
i lang:
print(i
Output:
)
pythonlistopdemo3.p
Thelist items
y
are
pytho
n c
java
php
List Functions &
Methods
List Functions & Methods
• Pythonprovidesvariousin-builtfunctions
inPython
can be used with list.
andmethodswhich
•
Those are • append • count
len() • () • ()
• • remov • index
max() • e() • ()
• sort() • insert
☞ min() reverse ()
• () pop()
• Insum()
len():Python, len() function is used to find the length
clear(
of• list()
list,i.e it )
returns the
Syntax: number of items in the list..
len(list
Example: listlendemo. Output:
)
num=[1,2,3,4,5,6]
py pythonlistlendemo.py
print("length of length of list:6
list :",len(num))
List Functions & Methods Cont
..
☞ max
inPython
():
• InPython, max() function is used to find maximum
Synta max(list
value in the list.
)
x:Exampl listmaxdemo
.py
list1=[1,2,3,4,5,6]
e:
list2=['java','c','python','cpp
'] print("Max of
list1 :",max(list1)) print("Max
of list2 :",max(list2))
Outpu
python
listmaxdemo.py
Max of list1
t:
Max of list2 :
python
:6
List Functions & Methods Cont
..
☞ min
inPython
():
• InPython, min() function is used to find minimum
Synta min(list
value in the list.
x: )
Exampl listmindemo.
e: py
list1=[1,2,3,4,5,6]
list2=['java','c','python','cpp
'] print("Min of
list1 :",min(list1)) print("Min
of list2 :",min(list2))Output: python
listmindemo.py Min of
list1 : 1
Min of list2 : c
List Functions & Methods Cont
..
☞ sum
inPython
•Inpython,
(): sum() function returns sum of all values in
values
the must in number
list. List
type.
Synta sum(list
x: )
Example: listsumdemo.py
list1=[1,2,3,4,5,6] print("Sum of
list items :",sum(list1))
Outpu
t:
python
listsumdemo.py
Sum of list items :
List Functions & Methods Cont
..
☞ list
inPython
():
• Inpython, list() is used to convert given sequence
into
(string or tuple)
list.
Synta list(sequence
x: )
Example:
listdemo.py
str="python"
list1=list(str)
print(list1) Output: python
listdemo.py
['p','y', 't', 'h',
List Functions & Methods Cont
..
☞ append
inPython
•Inpython,
(): append() method adds an item to the end
of the list. list.append(ite
Synta
whereitem may m) be number, string, list
x:
and etc. appenddemo.
Exampl
py
num=[1,2,3,4,5]
e:
lang=['python','java
'] num.append(6) Output:pythonappendde
print(num) mo.py
lang.append("cpp") [1, 2, 3, 4, 5, 6]
print(lang ['python', 'java', 'cpp']
)
List Functions & Methods Cont
..
☞ remove
inPython
•Inpython,
(): remove() method removes item from the list.
first occurrence of item if list contains duplicate items.
It removes
It throws an
error if thelist.remove(ite
Synta item is not present in the list.
x: m)
Example: removedemo.py
list1=[1,2,3,4,5]
list2=['A','B','C','B','D’] Output:
python
removedemo.py
list1.remove(2)
print(list1)
list2.remove("B") [1, 3, 4, 5]
print(list2) ['A','C', 'B', 'D']
list2.remove("E")
print(list2) ValueError: x not
in list
List Functions & Methods Cont
..
☞ sort()
inPython
•Inpython,
: sort() method sorts the list elements into
ascendingor
descending order. By default, list sorts the elements
into ascending
order. It takes an optional parameter 'reverse' which
sorts the list
Synta list.sort([reverse=true
into descending order.
Example:
x:
sortdemo.py ])
list1=[6,8,2,4,10]
list1.sort() Outpu
t:
python
print("\n After Sorting:\
sortdemo.py
n")
print(list1) After Sorting:
[2,4, 6,8,10]
print("Descending Order:\
Descending
n") Order:
list1.sort(reverse=True)
List Functions & Methods Cont
..
☞ reverse
inPython
•Inpython,reverse()
(): method reverses elements of the
last
list. i.e.index
the value of the list will be present at
0th index.
Synta list.reverse(
Example: )
x:
list1=[6,8,2,4,10]
reversedemo.py
list1.reverse()
print("\n After reverse:\
n") print(list1)
Output: python
reversedemo.py
After reverse: [10,4, 2,8,6]
List Functions & Methods Cont
..
inPython
☞ count(
• In): python, count() method returns the number of times
anelement
appears in the list. If the element is not present in the
list, it
Synta list.count(ite
returns 0.
x: m)
Example: countdemo.py
num=[1,2,3,4,3,2,2,1,4,5,8
] cnt=num.count(2)
print("Count of 2
is:",cnt)
cnt=num.count(10) Output:
print("Count of 10 pythoncountdemo.py
is:",cnt) Count of 2 is:3
Count of 10 is:0
List Functions & Methods Cont
..
inPython
☞ index(
• In): python, index () method returns index of the
the element
passed is not
element. If present, it raises a
ValueError.
• If list contains duplicate elements, it returns index of
occurred
element.
first
• This method takes two more optional parameters start
which are used to search index
within a limit.
and
Synta end list. index(item [, start[,
Example: indexdemo.py Output:
x: end]])
list1=['p','y','t','o','n','p pythonindexdemo
'] .py
print(list1.index('t')) 2
Print(list1.index('p')) 0
Print(list1.index('z' )
Print(list1.index('p',3,10)) 5
List Functions & Methods Cont
..
inPython
☞ insert(
• In
): python, insert() method inserts the element at the
specified
index in the list. The first argument is the index of the
element
Synta list.insert(index,ite
before which to insert the element.
x: m)
Example:
insertdemo.py
num=[10,20,30,40,5
0] Output: python
num.insert(4,60)
insertdemo.py
print(num)
[10, 20, 30, 40, 60, 50]
num.insert(7,70)
[10, 20, 30, 40, 60, 50,
print(num)
70]
List Functions & Methods Cont
..
inPython
☞ pop(
• In): python, pop() element removes an element present
at index from the
specified
list.
Syntax list.pop(index
Example:
: )
popdemo.py
num=[10,20,30,40,5
0]
num.pop() Output: python
print(num) popdemo.py
num.pop(2) [10, 20, 30, 40]
print(num) [10, 20, 40]
num.pop(7) IndexError:Out of range
print(num)
List Functions & Methods Cont
..
inPython
☞ clear(
• ):
It clears the list completely and returns
Inpython,clear()methodremovesalltheelementsfromtheli
nothing.
st.
Syntax list.clear(
Example:
: )
cleardemo.py
num=[10,20,30,40,5
0]
num.clear() Output: python
print(num) cleardemo.py
[]
QUIZ QUESTIONS
1. Which of the following creates an empty list?
a) list = ()
b) list = {}
c) list = []
d) list = ""
Answer: c
2. What is the output of:
mylist = list("abc")
print(mylist)
a) ['abc']
b) ['a', 'b', 'c']
c) ('a', 'b', 'c')
d) {'a', 'b', 'c'}
Answer: b
3. Which of these creates a list with one element: the string "apple"?
a) ["apple"]
b) list("apple")
c) ("apple")
d) {'apple'}
Answer: a
a) list(range(1,
4.How can you create a list from the range of numbers 1 to 5?
6))
b) list(range(1,
5))
c) range(1, 5)
d) range[1,6]
Answer: a
5. What is the output of:
a = [10, 20, 30, 40, 50]
print(a[2])
a) 10
b) 20
c) 30
d) 40
Answer: c
6. Which index accesses the last element of a list 1 ?
a) l[0]
b) l[-1]
c)
l[len(l)]
d) l[1]
Answer: b
7.What is the output of a[-3] if a = [3, 6, 9, 12,
15]?
a) 6
b) 9
c) 12
d) 15
Answer: b
8. Which slice gives the middle three elements
a) nums = [1, 2, 3, 4, 5, 6,7]?
from
nums[2:5]
b)
nums[1:4]
c)
nums[1:3]
d)
nums[3:6]
Answer: a
9. What does [1, 2] + [3, 4]
return?
a) [1, 2, 3, 4]
b) [[1, 2], [3,
4]]
c) [1, 2][3, 4]
d) Error
Answer: a
10. What is the output of:
[0] * 3
a) [0, 0,
0]
b) [0, 3]
c) [3, 3,
3]
d) Error Answer: a
11. Which of these expressions checks if 5
is in the list a = [1, 3, 5, 7]?
a) 5 in a
b)
a.contains(5)
c) a.has(5)
d) a == 5
Answer: a
12.What is the result of:
[1, 2, 3] * 2
a) [1, 2, 3, 1, 2,
3]
b) [2, 4, 6]
c) [1, 2, 3, 2]
d) Error
Answer: a
13.What is the output of len([10, 20,
30])?
a) 2
b) 3
c) 30
d) Error
Answer: b
14. What does sum([1, 2, 3, 4])
return?
a) 10
b) 1234
c) Error
d) [1, 2, 3,
4]
Answer: a
15. Which function returns the largest
number in a list?
a) high()
b) top()
c) max()
d)
upper()
Answer: c
16. Which of the following is not a built-
in function for lists?
a) min()
b) sort()
c)
append()
d) push()
Answer: d
17. Which method adds an item to the end of
a list?
a) add()
b)
append()
c) insert()
d)
extend()
Answer: b
18. What does list.pop() do?
a) Removes and returns the first element
b) Removes and returns the last element
c) Deletes the list
d) Adds a value to the list
Answer: b
19. How do you remove the first occurrence
of a)
a value from a list?
delete()
b)
remove(value)
c)
discard(value)
d) pop(value)
Answer: b
20. Which method inserts an item at a specific
position in a list?value)
a) add(index,
b) append(index,
value)
c) insert(index,
value)
d) extend(index,
Answer: c
value)
Thank you..