1 of 56

LIST MANIPULATION

2 of 56

  • 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 python. In other words, the memory address of a list will not change even after you change its values.

  • Python will not create a fresh list when you make any changes.

3 of 56

List

  • A list is a collection which is ordered and changeable. In Python lists are written with square brackets.

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

print(thislist)

output

['apple', 'banana', 'cherry']

4 of 56

MUTABLE & IMMUTABLE TYPES

Immutable –int , float, str, Boolean , tuple

Mutable – List, Dictionary, set

5 of 56

Creating and Accessing List

  • [] # List with no members, emptyList
  • [1,2,3] # list of integers
  • [1,2.4,6.8,2.1] #List of numbers
  • [‘a’,’b’,’c’] #list of characters
  • [‘One’,’Two’,’Three’] #List of strings
  • [‘a’,1,”hello”,5.78] #List of mixed value type

6 of 56

Types of list

  • Empty list

L=[] or L=list()

Long list

LL=[1,2,4 ……… ]

Nested List: A list inside a list

NL=[1,2,[‘A’,’B’],4,5]

7 of 56

Creating a list

  • You can use the built in type object to create lists from sequences as per the syntax
  • L = list(<sequence>)
  • sequence can be any kind of sequence object including strings, tuples and lists.

8 of 56

Program Output

9 of 56

10 of 56

11 of 56

Accessing List

  • List are sequences just like strings, they also index their individual elements just like strings do i.e it has forward indexing and backward indexing.

12 of 56

Operators and functions in List are

  • len() : Will return the number of items/ elements in the list
  • Indexing and slicing :

L[i] : returns the item at the index i (The first item has index 0]

L[i:j] : returns a new list , containing the objects at indexes between i and j (excluding index j)

Membership operators : Both in and not in operators works on list just like the way they work in strings

13 of 56

Traversing a List

  • The for loop makes it easy to traverse or loop over the items in a list, as per following syntax:

for <item> in <List> :

process each item in list

14 of 56

Traversing a List

  • The for loop makes it easy to traverse or loop over the items in a list, as per following syntax:

process each item in list

for i in range(len(L)):

print(L[i])

15 of 56

List operations

  • Joining List
  • Replicating List
  • Slicing List

16 of 56

  • Concatenation : (+) this adds one list to the end of the another list

JOINING LISTS

17 of 56

  • The + operator when used with List requires both the operands must be of list type. The following expression will result in error

list+number

list+string

list+complex-number

18 of 56

Replicating or Repeating List

  • Replication operators (*) : will repeat the list

19 of 56

SLICING THE LIST

  • seq=L[start:stop:step]

20 of 56

PROGRAM OUTPUT

21 of 56

PROGRAM OUTPUT

22 of 56

PROGRAM OUTPUT

23 of 56

Program

  1. Enter a list of numbers and add 2 to every item in the list and print the list in the end
  2. Enter a list of numbers and enter another number to be searched and print its position in the list (Do not use built in function)
  3. Enter a list of numbers and print the sum of all the numbers in the list

24 of 56

4. Enter the list and print the even numbers

5. Enter a list of numbers and print the sum of all the odd numbers in the list

6. Enter two list of numbers and form a new list such that the odd positions should be the numbers in the first list and even positions should be the numbers in the second list.(Assume both the list are of the same length)

7. Enter a list of numbers and print largest number in the list.

25 of 56

8. Enter a list of numbers and print largest number in the list. (Do not use in built functions)

9. Enter a list of Strings and print the string with the smallest length in the list.

(Do not use in built functions)

10. Create a list with n terms of fibonacci series.

26 of 56

List functions and methods

The general syntax for list functions and method is:

<list Object>.<method name>()

  1. The index method:

used as list.index(<item>)

eg: L1=[12,13,14,15]

print(L1.index(14))

Ans: 2

27 of 56

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

print(L1.index(18))

Ans : 1

print(L1.index(33))

Ans: Error #Value Error

28 of 56

2. The append method

Syntax : List.append(<Item>) # item means the value

It adds an element to the end of the list.

eg: L1=[12,’hello’,’@@’]

L1.append(“Python”)

print(L1)

Ans:

[12, 'HELLO', '@@', 'Python']

29 of 56

3. The extend method

Syntax is list.extend(<list>)

This takes a list as an argument instead of an item and adds to the end of the existing list

eg t1=[‘a’,’b’,’c’]

t2=[‘c’,’d’]

t1.extend(t2)

print(t1)

[‘a’,’b’,’c’,’c’,’d’]

30 of 56

Difference between append and extend

While append() function adds one element to a list, extend() can add multiple elements from a list passed as an argument

t1=[1,3,5]

t2=[7,8]

t1.append(10)

print(t1)

t1.append(12,14)

print(t1)

t1.extend(12)

print(t1)

t1.extend(t2)

print(t1)

31 of 56

t1=[1,3,5]

t1.append([12,13])

print(t1)

Ans: [1,3,5,[12,13]]

print(len(t1))

Ans: 4

t1=[1,3,5]

t1.extend([14,15])

print(t1)

Ans: [1,3,5,14,15]

print(len(t1))

Ans: 5

32 of 56

4. The insert method

  • Both the append and extend method insert the elements at the end of the list. Insert method will help you to insert the element at any position of your given choice.
  • syntax is:
  • List.insert(<pos>,<item>)
  • Here <pos> is the index value

33 of 56

L1=[‘a’,’e’,’o’]

L1.insert(2,’p’)

print(L1)

Ans: [‘a’,’e’,’p’,’o’]

L1.insert(-9,’k’)

print(L1)

Ans: [‘k’,‘a’,’e’,’p’,’o’]

Note: If the index is less than 0 and not equal to any of the valid negative indexes of the list then the value is prepended i.e added in the beginning of the list.

34 of 56

  • Similarly if the index is greater than the length of the list then the item is appended.
  • Write the to insert the item at the end of the list using insert method
  • L1.insert(len(L1),’g’)

35 of 56

5. The pop method

  • This will remove an item from the list, Syntax is
  • List.pop(<index>) #<index is optional>
  • This method will take one optional argument and returns a value – the item being deleted
  • The pop method will raise an exception(runtime error) if the list is already empty.
  • Eg t1=[]
  • t1.pop()
  • Error

36 of 56

L1=[10,20,30,40,50]

x=L1.pop(0)

print(x)

Ans 10

x=L1.pop()

print(x)

Ans: 50

print(L1)

Ans: [20,30,40]

37 of 56

6. The remove method

  • While pop removes an element whose position is known to you, remove method will remove based on the value given to you.
  • The remove method removes the first occurrence of the given item from the list.
  • List.remove(<item>)
  • It takes an item as an argument and does not return any value back

38 of 56

L1=[10,20,30,40,50]

L1.remove(20)

print(L1)

Ans: [10,30,40,50]

L1.remove(40)

print(L1)

Ans: [10,30,50]

L1.remove(80)

error as 80 not an item in the list (ValueError)

39 of 56

7. The clear method

  • This method removes all the items from the list and the list will become empty list after that. This function will not return anything
  • Syntax is L1.clear()
  • eg L1=[10,20,30]
  • L1.clear()
  • print(L1)
  • Ans []

40 of 56

8.The count method

  • This function returns the count of the item passed as an argument. If the given item is not there in the list, it returns a 0
  • Syntax : List.count(<item>)
  • L1=[1,2,4,3,2,1,2]
  • print(L1.count(2))
  • Ans 3
  • print(L1.count(5))
  • Ans 0

41 of 56

9. The reverse method

  • This will reverse the items in the list. This is done “in place” that means it will not create a new list
  • Syntax is List.reverse()
  • L1=[10,20,30,40,50]
  • L1.reverse()
  • print(L1)
  • Ans [50,40,30,20,10]

42 of 56

10. The sort method

  • This will sort the items in the list , by default in ascending order. This is done “in place” that means it will not create a new list
  • Syntax : List.sort()
  • t1=[90,49,0,23,45,12]
  • t1.sort()
  • print(t1)
  • Ans [0,12,23,45,49,90]

43 of 56

  • To sort the list in decreasing order the syntax is List.sort(reverse=True)
  • t1=[‘e’,’i’,’q’,’a’,’q’,’p’]
  • t1.sort(reverse=True)
  • print(t1)
  • Ans [‘q’,’q’,’p’,’i’,’e’,’a’]

44 of 56

45 of 56

Programs

  1. To calculate the mean of the given list of numbers
  2. Find the largest and the smallest numbers from a list of integers.
  3. To find the minimum element from the list along with its index in the list
  4. To search for an element from the list, user enters the number to be searched.
  5. Program to find the frequency of a given number for the list

46 of 56

6. Program to create a list in the following pattern

[10,5,20,15,30,25….N] where N is the number of elements in the list.

7. Program to display the frequency of all the elements in the list.

  1. Program to input a list of numbers and shifts all the zeros to the right and all non zero elements to the left of the list

9.Write a menu driven program to perform the following

1. Accept a list

2. search for an element in the list

3. Delete the element when index is given

4. Delete the element when value is given

5. Insert the element at any position

6. Display the list

7. Exit

47 of 56

48 of 56

10. Accept a List from the user, sort the list in ascending order and accept a new number and insert the number according to its proper position.

Eg : L=[45,12,3,56,90,52]

Sorted List = [3,12,45,52,56,90]

Accept a new number 60

Final list is = [3,12,45,52,56,60,90]

49 of 56

11. Write a menu driven program to do the following:

  1. Accept a string to a list.
  2. Print the strings that have less than 5 characters
  3. Ask for the index and check if the string is pallendrome
  4. Print the strings that are starting with character ‘a’ or ‘A’.
  5. Exit

50 of 56

  • Python sorted() function returns a sorted list from the iterable object.
  • Sorted() sorts any sequence (list, tuple) and always returns a list with the elements in a sorted manner, without modifying the original sequence

51 of 56

  • Parameters: sorted takes three parameters from which two are optional. 
  • Iterable : sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted.
  • Key(optional) : A function that would server as a key or a basis of sort comparison.
  • Reverse(optional) : If set true, then the iterable would be sorted in reverse (descending) order, by default it is set as false.

  • Python sorted() key
  • sorted() function has an optional parameter called ‘key’ which takes a function as its value. This key function transforms each element before sorting, it takes the value and returns 1 value which is then used within sort instead of the original value. For example, if we pass a list of strings in sorted(), it gets sorted alphabetically. But if we specify key = len, i.e. give len function as key, then the strings would be passed to len, and the value it returns, i.e. the length of strings will be sorted. Which means that the strings would be sorted based on their lengths instead

52 of 56

53 of 56

Two Dimensional List

  • A two dimensional list is a list having all its elements as lists of same shapes i.e 2D list is a list of lists
  • Eg L=[[10,20],[30,40],[50,60]]
  • Here L is a 2D list as it contains 3 elements each having the same shape (ie each nested list has len=2)

54 of 56

Regular 2D lists are the nested lists with these properties:

  1. All the elements of a 2D list should have same shape
  2. The length of a 2D lists tells us about Number of Rows in it(i.e len(L))
  3. The length of a single row gives us Number of columns (i.e len(L[i]))

55 of 56

Ragged List

  • A list that has lists with different lengths as its element is also a 2D list but it is an irregular 2D list also known as Ragged List.
  • L2=[[10,20,50],[40,10]] #ragged list

  • L = [10,20,[90,34]] #Not a 2D list it’s a single

56 of 56