Home » LIST MANIPULATION

LIST MANIPULATION

The python lists are containers that are used to store a list of values of any type. Unlike other variables Python lists are mutable i.e., you can change the elements of a list in place; Python will not create a fresh list when you make changes to an element of a list. List is a type of sequence like strings and tuples but it differs from them in the way that lists are mutable but strings and tuples are immutable.

CREATING AND ACCESSING LISTS

A list is a standard data type of Python that can store a sequence of values belonging to any type. The lists are depicted through square brackets.

[ ]                                # list with no member, empty list

[1,2,3]                          # list of integers

[1,2.0,3.5]                    #list of numbers

[‘a’,’b’,’c’]                    #list of characters

[‘one’,’two’,’three’]     #list of strings

[‘a’,1,5.5,’zero’]           #list of mixed value types

The memory address of a list will not change even after you change its values.

CREATING LISTS

Thus to create a list you can write in the form given below:

L=[ ]

L=[value,…..]

This construct is known as list display construct.

Consider some more examples:

  • The empty list:  The empty list is [ ]. It is the list equivalent of 0 or ‘ ‘ and like them it also has truth value as false. You can also create an empty list as:

L=list()

            It will generate an empty list and name that list as L.

  • Long lists: If a list contains many elements, then to enter such long lists, you can split it across several lines, like below:

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

            Notice the opening square bracket and closing square brackets appear just in the beginning and end of the list.

  • Nested lists: A list can have an element in it, which itself is a list. Such a list is called nested list, e.g.,

L1=[3,4,[5,6],7]

L1 is nested list with 4 element: 3, 4, [5, 6] and 7. L1[2] element is a list [5, 6]. Length of L1 is 4 as it counts [5,6] as one element. Also, as L1[2] is a list (i.e., [5,6]), which means L1[2][0] will give 5 and L1[2][1] will give 6.

Creating list from existing sequences

You can also use the built-in list type object to create lists from sequences as per the syntax given below:

            L=list(<sequence>)

Where <sequence> can be any kind of sequence object including strings, tuples, and lists. Python creates the individual elements of the list from the individual elements of passed sequence. If you pass in another list, the list function makes a copy.

Consider the following examples:

>>> l1=list(‘hello’)

>>>l1

[‘h’, ‘e’, ‘l’, ‘l’, ‘o’]

>>>t=(‘w’, ‘e’, ‘r’, ‘t’, ‘y’)

>>>l2=list(t)

>>>l2

[‘w’, ‘e’, ‘r’, ‘t’, ‘y’]

You can use this method of creating lists of single characters of single digits via keyboard input. Consider the code below:

>>>l1=list(input(“Enter list elements:”))

Enter list elements:171105

>>>l1

[‘1’, ‘7’, ‘1’, ‘1’, ‘0’, ‘5’]

Notice, this way the data type of all characters entered is string even though we entered digit. To enter a list of integers through keyboard, you can use the method given below:

Most commonly used method to input lists is eval(input()) as shown below:

list=eval(input(“Enter list to be added:”))

print(“List you entered:”,list)

when you execute it, it will work like:

Enter list to be added:17,18,25,16,23,26

List you entered:[17,18,25,16,23,26]

ACCESSING LISTS

Lists are mutable sequences having a progression of elements. There must be a way to access its individual elements and certainly there is. But before we start accessing individual elements, let us discuss the similarity of lists with strings that will make it very clear to you how individual elements are accessed in lists- the way you access string elements.

SIMILARITY WITH STRINGS

Lists are sequences just like strings that you read before. They also index their individual elements, just like strings do.

Thus, you can access the list elements just like you access a string’s elements e.g., List[i] will give you the element at ith index of the list; List[a:b] will give you elements betwwen indexes a to b-1 and so on.

Put in another words, Lists are similar to strings in following ways:

  • Length: function len(L) returns the number of items (count) in the list L.
  • Indexing and slicing: L[i] returns the item at index i (the first item has index 0), and 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 work on Lists just like they work for other sequences. That is, in tells  if an element is present in the list or not, and not in does the opposite.
  • Concatenation and replication operators + and * : The + operator adds one list to the end of another. The * operator repeats a list.

DIFFERENCE FROM STRINGS

Although lists are similar to strings in many ways, yet there is an important difference in mutability of the two. Strings are not mutable, while lists are.

TRAVERSING A LIST

Traversing a list also means the same and same is the tool for it, i.e., the python loops. That is why sometimes we call traversal as looping over sequence.

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 here

LIST OPERATORS

The most common operators that you perform with lists include joining lists, replicating lists and slicing lists.

Joining lists

Joining two lists is very easy just like you perform addition literally. The concatenation operator +, when used with two lists, joins two lists.

>>> lst1=[1,3,5]

>>>lst2=[6,7,8]

>>>lst1+lst2

[1,3,5,6,7,8]

The + operator when used with lists requires that both the operands must be of list types. You cannot add a number or any other value to a list. For example, following expression will result into error:

List + number

List + complex-number

List + string

Repeating or replicating lists

Like strings, you can use * operator to replicate a list specified number of times.

>>>lst1*3

[1,3,5,1,3,5,1,3,5]

Slicing the lists

>>>lst=[17,18,16,25,23,26]

>>>seq=lst[:-3]

>>>seq

[17,18,16]

>>>seq[2]=25

>>>seq

[17,18,25]

Lists also support slice steps. That is, if you want to extract, not consecutive but every other element of the list, there is a way out the slice steps.

>>>lst[0:10:2]

[17,16,23]

>>>lst[::-1]

[26,23,25,16,18,17]

MAKING TRUE COPY OF LIST

Sometimes you need to make a copy of a list and you generally tend to do it using assignment

a=[1,2,3,4]

a=b

It will not make b as a duplicate list of a; rather just like Python does, it will make label b to point where label a is pointing to.

It will work as long as we do not modify lists. Now, if you make changes in any of the lists, it will be reflected in other because a and b are like aliases for the same list.

You want both lists to be independent of each other. For this, you should create copy of the list as follows:

b= list(a)

There is another way of doing it, i.e., creating the true copy of a list, by using the copy() method. You can use the copy() method as follows:

L1=L.copy()

So, in nutshell, you can create a true copy of a list by using any one of the following three ways:

  1. By using the list() method.
  2. By using the copy() method.
  3. By storing all elements of the list using list slice in its copy.

METHODS IN LISTS

**lst.insert(index,item):To insert a new list item, without replacing any of the existing values, we can use the insert() method. returns no value

EXAMPLE 1:

thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)

OUTPUT:

[‘apple’, ‘banana’, ‘watermelon’, ‘cherry’]

EXAMPLE 2:

l1=['a','e','u']
l1.insert(-10,'i')
print(l1)

OUTPUT:

[‘i’, ‘a’, ‘e’, ‘u’]

**list.append(item): used to add an element to the end of the list.returns no value

EXAMPLE 1:

lst=[1,2,3]
lst.append(4)
print(lst)

OUTPUT:

[1, 2, 3, 4]

EXAMPLE 2:

lst=[1,3,5]
lst.append([2,4,6])
print(lst)

OUTPUT:

[1, 3, 5, [2, 4, 6]]

**list.extend(list):append elements from another list to the current list. returns no value

EXAMPLE 1:

thislist = ["apple", "banana", "cherry"]
thistuple = ("kiwi", "orange")
thislist.extend(thistuple)
print(thislist)

OUTPUT:

[‘apple’, ‘banana’, ‘cherry’, ‘kiwi’, ‘orange’]

EXAMPLE 2:

lst=['a','e','i']
lst.extend(['o','u'])
print(lst)

OUTPUT:

[‘a’, ‘e’, ‘i’, ‘o’, ‘u’]

**list.remove(value):The remove() method removes the specified item.returns no value

EXAMPLE 1:

lst=[1,2,3,4,5,6,7]
lst.remove(4)
print(lst)

OUTPUT:

[1, 2, 3, 5, 6, 7]

**list.pop(index):used to remove the item from the list.returns the value that is being deleted.

EXAMPLE 1:

lst=[1,2,3,4,5,6,]
s=lst.pop(4)
print(s)

OUTPUT:

5

EXAMPLE 2:


lst=[1,2,3,4,5,6,]
s=lst.pop()
print(s)

OUTPUT:

6

if no index is specified it removes and returns last element from the list. it raises an error if the list is empty

**del keyword

del list[index]: removes the element at index

EXAMPLE 1:

lst=[3,4,5,6,7,8]
del lst[5]
print(lst)

OUTPUT:

[3, 4, 5, 6, 7]

EXAMPLE 2:

lst=[18,17,16,25,23,26]
del lst[1:3]
print(lst)

OUTPUT:

[18, 25, 23, 26]

del listname : deletes all the elements and the list object too

EXAMPLE:

lst=['a','e','i','o','u']
del lst
print(lst)

OUTPUT:

NameError                                 Traceback (most recent call last)

Cell In[3], line 3

      1 lst=[‘a’,’e’,’i’,’o’,’u’]

      2 del lst

—-> 3 print(lst)

NameError: name ‘lst’ is not defined

**list.clear():this method removes all the items in the list and makes the list empty

EXAMPLE :


lst=['a','e','i','o','u']
lst.clear()
print(lst)

OUTPUT:

[]

**list.sort(reverse=True/False):sorts the items of the list by default in increasing order. this is done in place and it doesn’t create a new list

EXAMPLE 1:

lst=['vinny','sasi','anand','chinna']
lst.sort()
print(lst)

OUTPUT:

[‘anand’, ‘chinna’, ‘sasi’, ‘vinny’]

EXAMPLE 2:

lst=['vinny','sasi','anand','chinna']
T=lst.sort()
print(T)

OUTPUT:

None

**list.reverse():reverses the current order of elements.this is done in place

EXAMPLE:

lst=[1,3,5,'a','v']
lst.reverse()
print(lst)

OUTPUT:

[‘v’, ‘a’, 5, 3, 1]

**list=list1.copy():makes a true copy of a list

EXAMPLE:

lst=[25,50,75,100,125,150]
lst2=lst.copy()
print(lst2)

OUTPUT:

[ 25 , 50 , 75 , 100 , 125 , 150 ]

**list.index(item):returns the index of first matched item from the list.raises error if item is not in list.

EXAMPLE 1:

lst=[18,17,16,25,23,26]
print(lst.index(16))

OUTPUT:

2

EXAMPLE 2:

lst=[18,18,17,18]
print(lst.index(18))

OUTPUT:

0

**sorted(seq,reverse=True/False):it creates a new list containing the sorted version of list passed.it can take any iterable sequence type and returns a sorted “list.”

EXAMPLE 1:

val=(1,2,35,4,52,6)
sval=sorted(val)
print(sval)

OUTPUT:

[1, 2, 4, 6, 35, 52]

EXAMPLE 2:

val=['cat','ant','rat','rock','cake']
sval=sorted(val,reverse=True)
print(sval)

OUTPUT:

[‘rock’, ‘rat’, ‘cat’, ‘cake’, ‘ant’]