0% found this document useful (0 votes)
29 views31 pages

List

Uploaded by

bhikharilal0711
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views31 pages

List

Uploaded by

bhikharilal0711
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

Escape Character:

 To insert characters that are illegal in a string, use an escape character.


 An escape character is a backslash \ followed by the character you want to insert.
 An example of an illegal character is a double quote inside a string that is surrounded by
double quotes:
txt = "We are the so-called "Vikings" from the north." # ERROR
txt = "We are the so-called \"Vikings\" from the north."
Code Result
\' Single Quote
\\ Backslash
\n New Line
\r Carriage Return (returns the cursor to the beginning of the same line)
\t Tab
\b Backspace
\ooo Octal value
\xhh Hex value
List
 A list in Python is used to store the sequence of various (different) types of data, it is
very similar to arrays.

 Python lists are mutable type it means we can modify its element after it created.

 The items in the list are separated with the comma (,) and enclosed with the square
brackets [].

Ex:
l1 = ["John", 102, "USA"]
l2 = [1, 2, 3, 4, 5, 6]
print(l1)
print(l2)
print(type(l1))
print(type(l2))
O/P:['John', 102, 'USA']
[1, 2, 3, 4, 5, 6]
<class 'list'>
<class 'list'>

The list has the following characteristics:


o The lists are ordered.
o The element of the list can access by index.
o The lists are the mutable type.
o A list can store the number of various elements.
Ex:
a = [1, 2, "Peter", 4.50, 6]
b = [1, 2, "Peter", 4.50, 6]
print(a==b)
x = [1, 2, "Peter", 4.50, 6]
y = [2, 1, "Peter", 6, 4.50]
print(x==y)

O/P: True
False
 You access the list items by referring to the index number:

thislist = ["ABC", "XYZ", "PQR"]


print(thislist[1])

O/P: XYZ

 Negative indexing means beginning from the end, -1 refers to the last
item, -2 refer to the second last item etc.

thislist = ["ABC", "XYZ", "PQR"]


print(thislist[-1])

O/P: PQR
 You can specify a range of indexes by specifying where to start and
where to end the range.
 When specifying a range, the return value will be a new list with the
specified items.

thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])

O/P: ['cherry', 'orange', 'kiwi']


thislist = ["apple", "banana", "cherry", "orange", "kiwi",
"melon", "mango"]
print(thislist[0:7:2])
print(thislist[::2])

O/P: ['apple', 'cherry', 'kiwi', 'mango']


['apple', 'cherry', 'kiwi', 'mango']
Example:
list = [0,1,2,3,4,5]
print (list[-1]) #5
print (list[-3:]) # [3, 4, 5]
print (list[:-1]) # [0, 1, 2, 3, 4]
print (list[-3:-1]) # [3, 4]
 Updating List values

list = [1, 2, 3, 4, 5, 6]
print(list)
list[2] = 10
print(list)
list[1:3] = [89, 78]
print(list)
list[-1] = 25
print(list)

O/P: [1, 2, 3, 4, 5, 6]
[1, 2, 10, 4, 5, 6]
[1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
 Loop through a List

thislist = ["apple", "banana", "cherry"]


for x in thislist:
print(x, end=' ')

O/P: apple banana cherry


 Python List Operations:

Operator Description Example

The repetition operator


Repetition enables the list elements to be l1*2 = [1, 2, 3, 4, 1, 2, 3, 4]
repeated multiple times.

It concatenates the list


Concatenation mentioned on either side of l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8]
the operator.
It returns true if a particular
Membership item exists in a particular list print (2 in l1) prints True.
otherwise false.

for i in l1:
The for loop is used to iterate print(i, end = ’ ’)
Iteration
over the list elements. Output:
1234

It is used to get the length of


Length len (l1) = 4
the list
 Adding elements to the list - (Using append() and insert())
 Python provides append() function which is used to add an element to the list.
 However, the append() function can only add value to the end of the list.

Ex: taking the elements of the list from the user

l =[]
n = int(input("Enter the number of elements in the list:"))
for i in range (0, n):
l.append (input ("Enter the item:") )
print("printing the list items..")
for i in l:
print(i, end = " ")
O/P: Enter the number of elements in the list:4
Enter the item:11
Enter the item:22
Enter the item:abc
Enter the item:5.5
printing the list items..
11 22 abc 5.5

 To add an item at the specified index, use the insert() method:

thislist = ["apple", "banana", "cherry"]


thislist.insert(1, "orange")
print(thislist)

O/P: ['apple', 'orange', 'banana', 'cherry']


 Removing elements from the list - (remove(), pop(), del and
clear())
 Python provides the remove() function which is used to remove the element from
the list.
list = [0,1,2,3,4]
print(list)
list.remove(2)
print(list)

O/P: [0, 1, 2, 3, 4]
[0, 1, 3, 4]

If we write – list.remove(5)
It will give an error -list.remove(x): x not in list
 The pop() method removes the specified index, (or the last item if index is not
specified):

thislist = ["apple", "banana", "cherry", "mango"]


thislist.pop(1)
print(thislist)
thislist.pop()
print(thislist)

O/P: ['apple', 'cherry', 'mango']


['apple', 'cherry']
 The del keyword removes the specified index:

thislist = ["apple", "banana", "cherry", "mango"]


del thislist[2]
print(thislist)

O/P: ['apple', 'banana', 'mango']

 The del keyword can also delete the list completely:

thislist = ["apple", "banana", "cherry"]


del thislist
print(thislist) # this will cause an error

NameError: name 'thislist' is not defined


 The clear() method empties the list:

thislist = ["apple", "banana", "cherry"]


thislist.clear()
print(thislist)

O/P: []

 Copy a List:
 You cannot copy a list simply by typing list2 = list1, because: list2 will only be
a reference to list1, and changes made in list1 will automatically also be made in list2.
 There are ways to make a copy, one way is to use the built-in List method copy().
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)

O/P: ['apple', 'banana', 'cherry']

 Another way to make a copy is to use the built-in method list().

thislist = ["apple", "banana", "cherry"]


mylist = list(thislist)
print(mylist)

O/P: ['apple', 'banana', 'cherry']


 Join Two 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) # ['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:

list1 = ["a", "b", "c"]


list2 = [1, 2, 3]

for x in list2:
list1.append(x)

print(list1) # ['a', 'b', 'c', 1, 2, 3]


 you can use the extend() method, which purpose is to add elements from one list to
another list:

list1 = ["a", "b" , "c"]


list2 = [1, 2, 3]

list1.extend(list2)
print(list1) # ['a', 'b', 'c', 1, 2, 3]
 The list() Constructor
 It is also possible to use the list() constructor to make a new list.

thislist = list(("apple", "banana", "cherry"))


# note double round-brackets
print(thislist) # ['apple', 'banana', 'cherry']
 List Built-in functions:

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.
count() Returns the number of elements with the specified value.
Add the elements of a list (or any iterable), to the end of the
extend()
current list.
index() Returns the index of the first element with the specified value.
insert() Adds an element at the specified position.
pop() Removes the element at the specified position.
remove() Removes the item with the specified value.
reverse() Reverses the order of the list.
sort() Sorts the list.
len(list) It is used to calculate the length of the list.
max(list) It returns the maximum element of the list.
min(list) It returns the minimum element of the list.
list(seq) It converts any sequence to the list
Ex:

list1 = [1,2,3,4,5,2,3,2]
print(list1)

print("Count of 2 in list : ",list1.count(2))


print("First index of 2 in list : ",list1.index(2))

list1.reverse()
print("List in reverse order : ",list1)

list1.sort()
print("List in sorted order : ",list1)

print("Maximum element of list : ",max(list1))


print("Minimum element of list : ",min(list1))
O/P: [1, 2, 3, 4, 5, 2, 3, 2]
Count of 2 in list : 3
First index of 2 in list : 1
List in reverse order : [2, 3, 2, 5, 4, 3, 2, 1]
List in sorted order : [1, 2, 2, 2, 3, 3, 4, 5]
Maximum element of list : 5
Minimum element of list : 1

Ex:

Str = "ABCD"
list2 = list(str)
print (list2)
print (str)

O/P: ['A', 'B', 'C', 'D']


ABCD
1. Write the program to remove the duplicate element of the list.

list1 = [1,2,3,4,5,2,3,2]
list2=[]
for i in list1:
if i not in list2:
list2.append(i)
print(list2)

2. Write a program to find the sum of the element in the list.

list1 = [1,2,3,4,5,2,3,2]
sum=0
for i in list1:
sum=sum+i
print(sum)
3. Write the program to display elements of list which occurs more than
once.

list1=[1,2,3,4,5,3,6,7,3,5,3,1]
list2=[]
for i in range(0,len(list1)):
for j in range(i+1,len(list1)):
if list1[i]==list1[j] and list1[i] not in list2:
list2.append(list1[i])
break
print(list2)
OR

list1=[1,2,3,4,5,3,6,7,3,5,3,1]
list2=[]
for i in list1:
if list1.count(i)>1 and i not in list2:
list2.append(i)
print(list2)

You might also like