0% found this document useful (0 votes)
3 views11 pages

List Manipulation

The document provides a comprehensive overview of list manipulation in Python, detailing the characteristics, creation, and various operations that can be performed on lists. It covers list types, accessing elements, list functions and methods, and includes examples for clarity. Additionally, it highlights the differences between lists and strings, as well as the use of the eval() function, while cautioning against its use due to potential issues.
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)
3 views11 pages

List Manipulation

The document provides a comprehensive overview of list manipulation in Python, detailing the characteristics, creation, and various operations that can be performed on lists. It covers list types, accessing elements, list functions and methods, and includes examples for clarity. Additionally, it highlights the differences between lists and strings, as well as the use of the eval() function, while cautioning against its use due to potential issues.
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/ 11

LIST MANIPULATION

LIST
• The Python list are containers that are used to store a list of values of any type.
• Python list are mutable i.e. you can change the elements of a list in place

SOME LIST IN PYTHON


• [ ] – List with no member , empty list
• [ 1 , 2 , 3 ] – List of Integers
• [ 1, 2.5 , 3.7 , 9] – List of numbers (Integer & Floating point)
• [ „a‟ , „b‟ , „c‟ ] – List of characters
• [„a‟ , 1 , „b‟ , 3.5, „zero‟] – List of mixed value type
• [„one‟ , „two‟ , „three‟ ] – List of strings

CREATING LIST
• To create list, put a number of expressions in square brackets. i.e. use square
brackets to indicate start & end of the list, and separate the items by commas.
• Eg: [ 2 , 4 , 6 ]

SOME LIST IN PYTHON

EMPTY LIST: It is the list equivalent of 0 or „‟


L=[]

LONG LIST: If a list contains many elements.


Sqrs=[0,1,4,9,16,25,36,49,64,81,100,121,144,169,196,225,256,289,324,361,400,441,
484]

NESTED LISTS: A list can have an element in it, which itself is a list. Such a list is
called nested list.
Eg: L1 = [3 , 4 , [5 , 6] , 7]
L1 is a nested list with four elements: 3 , 4 , [5,6] and 7. L1[2] elements is a list [5,6]

CREATING LIST FROM EXISTING SEQUENCE


We can also use the built-in list type object to create lists from sequence as per the
syntax. Where sequence can be string, tuples and lists.
Syntax: L = list(sequences)
Eg: >>> L1 = list („hello‟)
>>>L1
>>> [ „h‟ , „e‟ , „l‟ , „l‟ , „o‟]
List L1 created from another sequence –string „hello‟

Eg: >>> T= („w‟ ,‟e‟ , „r‟ , „t‟ , „y‟)


>>> l2=list(T)
>>> l2
>>> [ „w‟ ,‟e‟ , „r‟ , „t‟ , „y‟]
List L2 is created from another sequence – a tuple

EVAL() FUNCTION

The eval() function of python can be used to evaluate and return the result of an
expression given as string.
For Eg:
eval („5+8‟)
O/P: 13

y=eval(“3*10”)
print(y)
O/P: 30

Since eval() can interpret an expression given as string, you can use it with input()
too.
var1=eval(input(Enter value:”))
print(var1,type(var1))
>>> Enter value: 75
>>> 75 <class „int‟>

var1=eval(input(Enter value:”))
print(var1,type(var1))
>>> Enter value: 89.9
>>> 89.9 <class „float‟>

var1=eval(input(Enter value:”))
print(var1,type(var1))
>>> Enter value: [l1,2,3]
>>> [1,2,3] <class „list‟>

var1=eval(input(Enter value:”))
print(var1,type(var1))
>>> Enter value: (2,4,6,8)
>>> (2,4,6,8) <class „tuple‟>
Note: Use of eval() method is always dicouraged because it leads to unforeseen
problems.

ACCESSING A LIST

SIMILARITY WITH STRING


• Length - len()
• Indexing & Slicing – L[i] : returns the item in index i
L[i:j] : returns the items between i & j
• Member ship operator – in & not in
• Concatenation & Repetition operator: „+‟ & „*‟

ACCESSING INDIVIDUAL ELEMENTS


>>> vowels=[„a‟ ,‟e‟ , „i‟, „o‟, „u‟]
>>> vowels [0] >>> „a‟
>>> vowels [4] >>> „u‟
>>> vowels [-1] >>> „u‟
>>> vowels [-5] >>> „a‟

Like string if you give index outside the legal indices. Python will raise Index Error
>>> vowels=[„a‟ ,‟e‟ , „i‟, „o‟, „u‟]
>>> vowels [5] >>> Index Error: list index out of range

DIFFERENCE FROM STRINGS


Although list are same like string in many ways, yet there is an important difference
in mutability of two. Strings are not mutable while list are.
>>> vowels=[„a‟ ,‟e‟ , „i‟, „o‟, „u‟]
>>> vowels[0]=„A‟
>>> [„A‟ ,‟e‟ , „i‟, „o‟, „u‟]
>>> vowels[-4]=„E‟
>>>[„A‟ ,‟E‟ , „i‟, „o‟, „u‟]

TRAVERSING A LIST
The for loop makes it easy to traverse or loop over the items in a list, as per the
syntax
Syntax: <item> in <list>:
process each item here

Eg: L=[„P‟,‟Y‟, „T‟ ,‟H‟ , „O‟, „N‟]


for a in L:
print(a)

PROGRAM TO PRINT ELEMENTS OF A LIST


L=[„q‟,‟w‟,‟e‟,‟r‟,‟t‟,‟y‟]
Length=len(L)
For a in range(Length):
print(“At indixes”,a, “and”, (a-length), “element:”, L[a])

COMPARING LIST
We can compare two list using standard comparision operator of python i.e. < ,> , ==,
!= etc. Python internally compares individual elements of list and (tuples) in
lexicographical order.
This means that to compare equal, each corresponding element must compare equal
and the two sequences must be of same type i.e. having comparable types of values.

L1=[1,2,3]
L2=[1,2,3]
L3=[1,[2,3]]
L1=L2
TRUE
L1==L3
FALSE

L1<L2
FALSE

L1<L3
TYPE ERROR

For first comparison, python did not give any error as both lists have values of same
type.
For second comparison, as the values are not of comparable types, python raised
error.

>>> a=[2,3]
>>> b=[2,3]
>>> c=[„2‟,‟3‟]
>>> d=[2.0,3.0]
>>> e=[2,3,4]

a==b TRUE
a==c FALSE
a>c FALSE
d<a FALSE
d==a TRUE

LIST OPERATIONS
The most common operations that you perform with list include joining lists,
replicating lists and slicing list.

JOINING LIST
L1=[1,3,5]
L2=[6,7,8]
L1+L2
>>> [1,3,5,6,7,8]

L1=[1,3,5]
L2=[6,7,8]
L3=[10,20,30]
L4=L1+L2+L3
>>> [1,3,5,6,7,8,10,20,30]

NOTE: The + operator when used with lists requires that both the operands must
be of list types.
For Eg: Following expression will result into error.

List + number
List + complex number
List + string

L1+2 >>> ERROR


L2+”abc” >>> ERROR
REPEATING OR REPLICATING LISTS

L1=[1,2,3]
L1*3
[1,2,3,1,2,3,1,2,3]

Like strings, you can only use only integer with a * operator when trying to replicate
a list.

SLICING A LIST

List slices, like string slices are the sub part of a list extracted out.

Syntax: seq=L1[start:stop]

Eg:
L1=[10,12,14,20,22,24,30,32,34]
Seq=L1[3:-3]
>>> Seq
[20,22,24]
Seq[1]=28
>>>Seq
[20,28,24]

L1[start:stop] creates a list slice out of list L with elements falling between indexes
start and stop, not including stop.

L1=[10,12,14,20,22,24,30,32,34]
>>>L1[3:30]
[20,22,24,30,32,34]
>>>L1[-15:7]
[10,12,14,20,22,24,30]
>>>L1[2,3,4,5,6,7,8]
>>>L1[2:5]
[4,5,6]
>>>L1[6:10]
[8]
>>>L1[10:20] # Both limits are out of bound
[]
List also supports slice steps. The slice steps are used as per following format:
Seq=L1[start:stop:step]

L1=[10,12,14,20,22,24,30,32,34]

>>>L1[0:10:2]
[10,14,22,30,34]

>>>L1[2:10:3]
[14,24,34]

>>>L1[ : : 3]
[10,20,30]

WORKING WITH LISTS

- Appending append() # To add or affix or join or attach


- Update
- Deleting

Appending elements to a list: The append() method adds a single item to the end of
the list.

Syntax: L.append(item)

Eg: L1=[10,12,14]
>>> L1.append(16)
>>.L1
>>> [10,12,14,16]

Updating Elements in a list: To update or change an element of the list in place, you
just have to assign new value to the elements index in the list.

Syntax: L[index]=<new value>

Eg: L1=[10,12,14,16]
>>>L1[2]=18
>>>L1
>>>[10,12,18,16]
Deleting elements from a list
We can also remove items from the list. The del statement can be used to remove an
individual item, or to remove all items identified by a slice.

del list[index]
del list[start:stop]

L1=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
Del L1[10]
>>>L1
[1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,19,20]

Del L1[10:15]
>>>L1
[1,2,3,4,5,6,7,8,9,10,17,18,19,20]

MAKING A COPY OF LIST

a=[1,2,3]
b=a

>>>a[1,2,3]
>>>b=a
>>>a[1]=5
>>>a
[1,5,3]
>>>b
[1,5,3]

See , along with a, list b is also modified.


HOW TO KEEP THE LIST B UNCHANGED????

a=[1,2,3]
b=list(a)
>>>a[1]=5
>>>a
[1,5,3]
>>>b
[1,2,3]
Now list b is not reflecting the changed value. List b is independent of list a.
LIST FUNCTIONS & METHODS
Python offers many built-in functions and methods for list manipulation.

1. index method: This function returns index of first matched item from the list.
Syntax: List.index(item)

Eg: L1=[13,18,11,16,18,14]

>>>L1.index(18)
1
Returns only the index value of first value 18, even if there is another value 18 at
index 4.

2. append method: Append() method adds an item to the end of the list.
Syntax: List.append(item)

colour=[„red‟,‟green‟,‟yellow‟]
colours.append(“blue”)
>>> colour[„red‟,‟green‟,‟yellow‟,‟blue‟]

3. extend method: The extend method is also used for adding mutltiple elements to a
list.
Syntax: List.extend(list)

>>> t1=[„a‟,‟b‟,‟c‟]
>>>t2=[„d‟,„e‟,‟f‟]
>>> t1.extend(t2)
>>>t1
[„a‟,‟b‟,‟c‟,‟d‟,‟e‟,‟f‟]

4. insert method: The insert() method is also an insertion method for lists, like
append and extend methods.
- Both append() & extend() method is used to insert the elements at end of list.
- If you want to insert an element in between or any position of your choice, for such
requirement we use insert() method.
Syntax: List.insert(pos, item)
Eg: t1=[„a‟,‟e‟,‟u‟]
t1.insert(2,i)
>>> t1
[„a‟,‟e‟,‟i‟,‟u‟]
5. The pop method: The pop() is used to remove the item from the list.
Syntax: List.pop(index)
t=[„p‟,‟r‟,‟a‟,‟v‟,‟e‟,‟e‟,‟n‟]
t.pop[5]
>>>t
[„p‟,‟r‟,‟a‟,‟v‟,‟e‟,‟n‟]

Note: If no index is specified, pop() removes and returns the last item in the list.
The pop() method raises an exception(runtime error) if the list is already empty.

6. The remove method: While pop() removes an element whose position is given.
This is method is used to delete the element when the value is known and the index
value is unknown.
The remove() will removes the first occurrence of given item from the list.
Syntax: List.remove(value)
T1=[‘a’,’e’,’o’,’i’,’e’,’b’,’c’]
T1.remove(‘e’)

7. The clear method: This method removes all the items from the list and the list
becomes empty list after this function.
Syntax: List.clear()
Eg: L1=[13,18,11,16,18,14]
>>> L1.clear()
>>>L1
[]

8. The count method: This function returns the count of the item that you passed as
argument. If the given item is not in the list, it returns zero.
Syntax: List.count(item)
Eg: L1=[13,18,20,10,18,23]
>>>L1.count(18)
2

9. The reverse method: The reverse() reverses the items of the list. This is done “in
place”, i.e. it does not create a new list.
Syntax: List.reverse()
Eg: L1=[13,18,20,10,18,23]
L1.reverse()
>>>L1
[23,18,10,20,18,13]
10. The sort method: The sort() function sorts the items of the list, by default in
ascending order. This is done “in place” i.e. it does not create a new list.
Syntax: List.sort()
L1=[13,18,20,10,18,23]
>>>L1.sort()
[10,13,18,18,20,23]

PROGRAM TO FIND MINIMUM ELEMENT IN THE LIST ALONG WITH INDEX


-----------------------------------------------------------------------------------------------------------
list=eval(input("Enter list:"))
length=len(list)
minele=list[0]
minind=0
for i in range(1,length-1):
if list[i]<minele:
minele=list[i]
minind=i
print("Givn list is:",list)
print("The minimum element of the given list is:", minele, "at index", minind)

PROGRAM TO CALCULATE THE MEAN OF A GIVEN LIST OF NUMBERS


----------------------------------------------------------------------------------------------------
list=eval(input("Enter list:"))
length=len(list)
print(length)
mean=tot=0
for i in range(0,length-1):
tot+=list[i]
mean=tot/length
print("Given list is:", list)
print("The mean of the given list is:",mean)

PROGRAM TO SEARCH FOR AN ELEMENT IN A GIVEN LIST OF NUMBERS


-------------------------------------------------------------------------------------------------------
lis=eval(input("Enter list:"))
length=len(lis)
element=int(input("Enter element to be searches:"))
for i in range(0,length-1):
if element==lis[i]:
print(element, "found at index", i)
break
else:
print(element, "not found in given list")

You might also like