0% found this document useful (0 votes)
15 views32 pages

List

bca python

Uploaded by

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

List

bca python

Uploaded by

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

Objects in Python

Everything in python is considered an object.

Every object has these three attributes:

 Identity – This refers to the address that the object refers to in

the computer’s memory.

 Type – This refers to the kind of object that is created. For

example- integer, list, string etc.

 Value – This refers to the value stored by the object. For example

– List=[1,2,3] would hold the numbers 1,2 and 3

We can't change the type of object but we can change the value of the

object.

For example, we set variable a as a list, now we can't change variable from

list to tuple/dictionary but we can change the values in that list.

There are two types of objects in python.

One, those objects which can change their internal state (the

data/content inside those objects) i.e. they can be changed with the help of

predefined functions or methods while on the other hand, those objects

which can't change their internal state(the data/content inside the

objects).
Mutable-Definition

Mutable is when something is changeable or has the ability to change. In

Python, ‘mutable’ is the ability of objects to change their values. These are

often the objects that store a collection of data.

Mutable means those objects which can change themselves after we

instantiate them. There are several methods and functions by which

we can change the mutable objects. By using those methods and

functions the original objects get modified.

While doing any changes to the mutable objects the memory at

which those objects are stored remains the same. This is explained in

different sections Mutable Objects.

Objects of built-in type that are mutable are:

 Lists

 Sets

 Dictionaries

 User-Defined Classes (depends upon the characteristics)

Immutable-Definition

Immutable is the when no change is possible over time. In Python, if the

value of an object cannot be changed over time, then it is known

as immutable. Once created, the value of these objects is permanent.

Immutable means those objects which can't change themselves after we

initialize them. There are no methods and functions which can be used

to modify those immutable objects. We have to convert those


immutable objects to the mutable once and then we can modify those

objects.

While doing any changes to the immutable objects, the memory at

which these objects were stored during initialization, gets updated.

This is explained in different sections Immutable Objects.

Objects of built-in type that are immutable are:

 Numbers (Integer, Rational, Float, Decimal, Complex & Booleans)

This means that after you create the object and assign some value

to it, you can’t modify that value.

 Strings

 Tuples

 Frozen Sets

 User-Defined Classes (purely depends upon the characteristics)

Example 1:

str1="Kalpana"

str1[0]="k"

print(str1)

Output:

TypeError: 'str' object does not support item assignment

Example 2:

a=1

print(id(a)) # address=9788992
a=2

print(id(a)) # address=9789024

Note:

Why are these values different if you’re using variable name a in both

cases?

Explanation:

The variable named a is bound to an object with value 1 in one memory

location. When the variable named a is bound to a different object with

value 2, the original object with value 1 is still in memory, but you can’t

access it anymore through a variable.

Mutable Immutable

The objects can be modified after the Objects can not be modified after

creation as well. the creation of the objects.

Classes are not made final for the Classes are made final for the

mutable objects. immutable objects.

Example: Lists, Dicts, Sets, User-Defined Example: int, float, bool, string,

Classes, Dictionaries, etc. Unicode, tuple etc.

Why care about Immutables ?


1. Improves the Exactness and simplicity of the whole code, as it provides an

ease to the coder to pass around the object in the program without any

fear as it never seems to be ever modified. whereas the mutable is much

harder to reason about. In mutable, the aliasing leads to many

irregularities and eventually intimidating fidelity of the code, At the end

resulting in variability.

2. Thread Safe – As an object after the assignment cannot be modified, this

deduces that a read-only data is being shared among the threads, which

certainly provides thread-safety. In simpler words, In immutables, since

there is no scope of change for an object, there is no need to be scared of

accessing it from many threads. Mutation in any sense in immutable

objects can be achieved in such a way that one creates a new object

instead of trying to modify existing ones.

Limitations

Over time, different conclusions get introduced with it, as we read that

Immutables is Thread safe, and no matter which thread reads their values,

They get the right values, but The immutables are found to be immune

to “Memory Consistency Errors”, that can be furthermore explained as;

Immutable objects by themselves are not thread-safe. It is the code that

uses them that must be written to be thread-safe. Simply using immutable

objects is not enough to achieve this. One has to also guard against

deadlock, livelock, and starvation.


List

A list can be defined as an object that contains multiple data items

(elements). The contents of a list can be changed during program execution.

The size of a list can also change during execution, as elements are added or

removed from it.

A list can grow and shrink during execution of the program. Hence it is also

known as a dynamic array. List is commonly used for handling variable

length data.

A list holds comma-separated values (items or elements) between square

brackets where items or elements need not all have the same type.Lists are

used to store multiple items in a single variable.

A list in Python is used to store the sequence of various types of data. Python

lists are mutable type its mean we can modify its element after it created.

Example 1:

colors=["red","green","blue"]

print(colors)

Output:

['red', 'green', 'blue']

Like this we can print all the elements of a list in one go.

We also have the option to print elements of list separately.

Example 2:

colors=["red","green","blue"]

print(colors[0])
print(colors[1])

print(colors[2])

Output:

red

green

blue

As soon as we define elements of list, they take numeric values as index

starting from 0.

colors = ['red', 'blue', 'green']

Here

print(colors[0]) ## red

print(colors[2]) ## green

print(len(colors)) ## 3

Example 3:

Lst1=[] #this is an empty list.

Characteristics of Lists

The list has the following characteristics:

o The lists are ordered (all elements have definite order/sequence, any

element added is added at the end).


o The element of the list can be access by index.

o A list can store the number of various elements (elements with

different data types can be added in the same list).

o List allows duplicate values (same element can be added multiple

number of times).

o List elements are changeable (we can add, delete item from the

list).

Loop through a List

We can also print elements of array using loops. In loop, in every iteration

one element of list is selected and printed, then another element is picked

and printed and so on till all the elements of list are complete.

Example 1: #using for loop

colors = ["green", "red", "blue", "yellow"]

for e in colors:

print(e)

Output:

green

red

blue

yellow

Example 2: #using while loop

colors = ["green", "red", "blue", "yellow"]


i=0

while i<len(colors):

print(colors[i])

i=i+1

Output:

green

red

blue

yellow

Negative Indexing

Usually the indexes start from left side and with numeric value zero. In

addition to this, in Python we have the concept of negative index also which

starts from right hand side.


Example:

colors = ["green", "red", "blue"]

print(colors[0])

print(colors[1])

print(colors[2])

print(colors[-1])

print(colors[-2])

print(colors[-3])

Output:

green

red

blue

blue

red

green

Note:You can use negative indexing as your advantage when you want to

pick values from the end (right side)

Print specific elements

Whenever we display a list using print command, all the elements of the list

gets printed starting from index value to 0 to n-1, where n is number of

elements. There may be a situation when we need to print specific elements

of the list. Specify start and End-1 as parameters.

Example :

colors = ["green", "red", "blue","pink","yellow","white"]


print(colors[2:5])

Output:

['blue', 'pink', 'yellow']

Note:

colors = ["green", "red", "blue","pink","yellow","white"]

print(colors[0:6]) Output:['green', 'red', 'blue', 'pink', 'yellow', 'white']

print(colors[:4]) Output: ['green', 'red', 'blue', 'pink']

print(colors[2:]) Output: ['blue', 'pink', 'yellow', 'white']

print(colors[0:8]) Output: ['green', 'red', 'blue', 'pink', 'yellow', 'white']

print(colors[0:-4]) Output: ['green', 'red']

print(colors[:-3]) Output: ['green', 'red', 'blue']

print(colors[-3:]) Output: ['pink', 'yellow', 'white']

print(colors[-4:-1]) Output: ['blue', 'pink', 'yellow']


Length of list

To determine the number of elements present in the list, we use len()

function:

Example:

colors=["red","green","blue"]

print(len(colors))

Output:

Data Type of a list

One can find the data type of a list with type() function. lists are defined as

objects with the data type 'list'. A list can contain any element of any data

type.

Example:

colors=["red","green","blue"]

print(type(colors))

mynumbers=[1,2,3]

print(type(mynumbers))

mybool=["TRUE","FALSE","FALSE"]

print(type(mybool))

Output:

<class 'list'>

<class 'list'>
<class 'list'>

Concept: A list can contain multiple elements with different data types.

Example:

mylist=["abc", 123, "FALSE",25.8,"xyz"]

print(mylist)

Output:

['abc', 123, 'FALSE', 25.8, 'xyz']

Concept: As list is mutable, it can be updated as shown below:

Example:

Lst1=["a","b","c","d","e"]

print(Lst1)

Lst1[2]="e" #element at index 2 will change

print(Lst1)

Lst1[2:4]=["g","h"] # element at index 2 and 3 will be inserted

print(Lst1)

Lst1[0:2]=[] # delete element at 0th and 1st index

print(Lst1)

Output:

['a', 'b', 'c', 'd', 'e']

['a', 'b', 'e', 'd', 'e']

['a', 'b', 'g', 'h', 'e']

['g', 'h', 'e']


Concept:A string can be converted into a list

Example:

Lst1=list(“List Topic”)

print(Lst1)

Output:

['L', 'i', 's', 't', ' ', 'T', 'o', 'p', 'i', 'c']

Concept: It is possible to create a list of list

Example:

a=[1,3,5]

b=[6,8,9]

c=[0,2,4]

d=[a,b,c]

print(d)

print(d[0][1])

print(d[2][1])

Output:

[[1, 3, 5], [6, 8, 9], [0, 2, 4]]

Concept:A list can be embedded in another list

Example:

X=[1,2,3]

Y=[10,20,X]

Print(Y)
print(Y[1])

print(Y[2])

Output:

[10, 20, [1, 2, 3]]

20

[1, 2, 3]

Concept: We can embed elements of list separately

Example:

X=[1,2,3]

Y=[10,20,*X]

print(Y)

print(Y[1])

print(Y[2])

Output:

[10, 20, 1, 2, 3]

20

List Methods

Python has a set of built-in methods that you can use on lists.

Metho Description
d

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

extend( Add the elements of a list (or any iterable), to the end of the

) 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

Append Items
Appending an element in the list means to add an element at the end. To

add an item to the end of the list, use the append() method:

Example 1:

#Appending one element at a time

colors = ["green", "red", "blue","pink","yellow"]

colors.append("silver")

print(colors)

Output:

['green', 'red', 'blue', 'pink', 'yellow', 'silver']

Example 2:

#Appending two element at a time. Both the elements will be added one

after another.

colors = ["green", "red", "blue","pink","yellow"]

colors.append("silver")

colors.append("golden")

print(colors)

Output:

['green', 'red', 'blue', 'pink', 'yellow', 'silver', 'golden']

Clear the List

The clear method is used to clear all the elements from the list.

The clear() method empties the list.The list still remains, but it has no

content.

Example:
colors = ["green", "red", "blue","pink","yellow"]

print(colors)

colors.clear()

print(colors)

Output:

['green', 'red', 'blue', 'pink', 'yellow']

[]

Copy a List

Copy a list means to copy elements of one list into another. If the contents/

elements of list are copied by = operator, then new list created will just be a

copy of original list. Whatever changes you make in original list will

automatically be applicable to new list because of = operator.

Example:

colors1 = ["green", "red", "blue","pink","yellow"]

colors2=colors1

print(colors2)

Output:

['green', 'red', 'blue', 'pink', 'yellow']

Another better approach is copy() method.

Example:

colors1 = ["green", "red", "blue","pink","yellow"]


colors2=colors1.copy()

print(colors2)

Output:

['green', 'red', 'blue', 'pink', 'yellow']

Count()

This method is used to count the number of times a element has occurred in

the list.

Example 1:

colors = ["green", "red", "blue","red","yellow"]

print(colors.count("red"))

Output:

Example 2:

colors = ["green", "red", "blue","red","yellow"]

print(colors.count("black"))

Output:

Extend()

Extend means to increase the total number of elements in the list by adding

another list at the end. To append elements from another list to the current

list, use the extend() method.

Example:

colors1 = ["green", "red", "blue"]


colors2= ["grey","black"]

colors1.extend(colors2)

print(colors1)

Output:

['green', 'red', 'blue', 'grey', 'black']

Index()

The index() method returns the position at the first occurrence of the

specified value. If any element is occurring more than once, then first

occurrence is considered.

Example 1:

colors = ["green", "red", "blue"]

print(colors.index("blue"))

Output:

Example 2:

colors = ["green", "red", "blue"]

print(colors.index("black"))

Output:

Error

Insert()

This method is used to insert an element at any particular location in the list.

To insert a new list item, without replacing any of the existing values, we can
use the insert() method. The insert() method inserts an item at the specified

index.

Example 1:

colors = ["green", "red", "blue","pink","yellow"]

print(colors)

colors.insert(2,"black")

print(colors)

Output:

['green', 'red', 'blue', 'pink', 'yellow']

['green', 'red', 'black', 'blue', 'pink', 'yellow']

Example 2:

colors = ["green", "red", "blue","pink","yellow"]

print(colors)

colors.insert("black")

print(colors)

Output:

Error

Example 3:

colors = ["green", "red", "blue","pink","yellow"]

print(colors)

colors.insert(8,"black")

print(colors)
Output:

['green', 'red', 'blue', 'pink', 'yellow']

['green', 'red', 'blue', 'pink', 'yellow', 'black']

Pop()

The pop() method removes the element by specifying specified index. The

element present at the specified index in popped out from the list.

Example 1:

colors = ["green", "red", "blue"]

popped=colors.pop()

print(colors)

print(popped)

Output:

['green', 'red']

blue

Example 2:

colors = ["green", "red", "blue"]

popped=colors.pop(0)

print(colors)

print(popped)

Output:
['red', 'blue']

green

Example 3:

colors = ["green", "red", "blue"]

popped=colors.pop(6)

print(colors)

print(popped)

Output:

Error

Remove()

This method is used to remove a particular element from the list.

Example 1:

colors = ["green", "red", "blue"]

colors.remove("blue")

print(colors)

Output:

['green', 'red']

Example 2:

colors = ["green", "red", "blue"]

colors.remove("pink")

print(colors)
Output:

Error

Pop() Vs Remove()

Pop() Remove()

It takes index number as argument It takes element as argument

Return the popped element Do no return removed the element

Reverse()

This method is used to arrange elements of list in a reverse order. The

element at index 0 will go to index n-1 and element at index n-1 will go to

index 0.

Example:

colors = ["green", "red", "blue", "yellow"]

colors.reverse()

print(colors)

Output:

['yellow', 'blue', 'red', 'green']

Sort()

Sometimes one may need to arrange all the elements of list in ascending or

descending order. List objects have a sort() method that will sort the list
alphanumerically in ascending or descending order. By default the order is

ascending.

Example 1: #character list is sorted in ascending order

colors = ["green", "red", "blue", "black"]

colors.sort()

print(colors)

Output:

['black', 'blue', 'green', 'red']

Example2: # number list is sorted in ascending order

mynum=[34,67,12,87,43]

mynum.sort()

print(mynum)

Output:

[12, 34, 43, 67, 87]

Example 3: #character list sorted in descending order

colors = ["green", "red", "blue", "yellow"]

colors.sort(reverse=1)

print(colors)

Output:

['yellow', 'red', 'green', 'blue']

Example 4: #number list sorted in descending order


mynum=[34,67,12,87,43]

mynum.sort(reverse=1)

print(mynum)

Output:

[87, 67, 43, 34, 12]

Concept:

In case of small and capital letters, we get unexpected answer while sorting.

colors = ["Green", "Red", "blue", "yellow"]

colors.sort()

print(colors)

Output:

['Green', 'Red', 'blue', 'yellow']

To perform case insensitive search write as:

colors = ["Green", "Red", "blue", "yellow"]

colors.sort(key=str.lower)

print(colors)

Output:

['blue', 'Green', 'Red', 'yellow']

Check if Item Exists

We can determine if a specified item is present in a list by using

the in keyword.

Example 1:
colors = ["green", "red", "blue","pink","yellow"]

if "red" in colors:

print("The color is present")

Example 2:

colors = ["green", "red", "blue","pink","yellow"]

if "black" in colors:

print("The color is present")

Change Particular element/elements from list

One may need to change the value of a single item or multiple elements

within a specific range. First you need to define a list with the new values,

and refer to the range of index numbers where you want to insert the new

values.

Example 1:

colors = ["green", "red", "blue","pink","yellow"]

print(colors)

colors[1] = "black"

print(colors)

Output:

['green', 'red', 'blue', 'pink', 'yellow']

['green', 'black', 'blue', 'pink', 'yellow']

Example 2:

colors = ["green", "red", "blue","pink","yellow"]

print(colors)
colors[2:4] = ["black","saffron"]

print(colors)

Output:

['green', 'red', 'blue', 'pink', 'yellow']

['green', 'red', 'black', 'saffron', 'yellow']

Example 3:

colors = ["green", "red", "blue","pink","yellow"]

print(colors)

colors[2:4] = ["black","saffron","grey"]

print(colors)

Output:

['green', 'red', 'blue', 'pink', 'yellow']

['green', 'red', 'black', 'saffron', 'grey', 'yellow']

Example 4:You can use negative indexing as your advantage when you

want to pick values from the end (right side)

colors = ["green", "red", "blue","pink","yellow"]

print(colors)

colors[2:4] = ["black"]

print(colors)

Output:

['green', 'red', 'blue', 'pink', 'yellow']

['green', 'red', 'black', 'yellow']

del()
This method is used to remove an element from a specific index number.

This method is also used to delete complete list, if required.

Example 1:

colors = ["green", "red", "blue"]

print(colors)

del colors[0]

print(colors)

Output:

['green', 'red', 'blue']

['red', 'blue']

Example 2:

colors = ["green", "red", "blue"]

print(colors)

del colors

print(colors)

Output:

['green', 'red', 'blue']

NameError: name 'colors' is not defined

Example 3:

colors = ["green", "red", "blue","magenta","pink"]

print(colors)

del colors[2:4]

print(colors)

Output:
['green', 'red', 'blue', 'magenta', 'pink']

['green', 'red', 'pink']

Join Two Lists

Python offers a very simple operator to join two lists, which is +. With just

the help of +operator 2 lists can be combined.

Example:

colors1 = ["green", "red", "blue"]

colors2=["black","white","grey"]

colors3=colors1+colors2

print(colors3)

Output:

['green', 'red', 'blue', 'black', 'white', 'grey']

Python List Built-in functions

Python provides the following built-in functions, which can be used with the

lists.
SN Function Description Example

1 cmp(list1, It compares the This method is not used in the

list2) elements of both the Python 3 and the above

lists. versions.

2 len(list) It is used to calculate L1 = [1,2,3,4,5,6,7,8]

the length of the list. print(len(L1))

3 max(list) It returns the L1 = [12,34,26,48,72]

maximum element of print(max(L1))

the list. 72

4 min(list) It returns the minimum L1 = [12,34,26,48,72]

element of the list. print(min(L1))

12

5 list(seq) It converts any str = "Johnson"

sequence to the list. s = list(str)

print(type(s))

<class list>

You might also like