Tuesday, December 29, 2020

List operations.

index in python always starts from 0

a=["sri",10,3.5,print] 

a[0]    //output: sri

a[3]    //output: print

a[3]("HelloWorld")    //output: HelloWorld

 

Some important properties of lists are

  • They are mutable

  • Ordered

  • Heterogenous

  • accessed using index

  • List are iterable

 for index in a:

        print(a[index])

output:   

10

20

30

40

50

a[-1] will give the last element   //  50

a[-2]  will give the second last element   //40

a[-3] will give the third last element and so on   //30

 

Some of the basic list operations

  • finding length
  • concatinate
  • repetition
  • membership
  • insert 
  • append
  • pop
  • remove
  • del
  • copy
  • count

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

1)Find Length: len(a)   output - 5 

2)Concatinate  (join two lists): a+a    output - [10,20,30,40,50,10,20,30,40,50]

3)Repetition  (repeat the same list number of times):  a*2    output - [10,20,30,40,50,10,20,30,40,50]

4)Membership  (check whether element is present in the list): 10 in a  output - True

 

Updating list elements

Inserting element into list:

  • insert

  • append

 

5)Insert operation:

insert operation inserts an element to list at a fixed index.

my_list=["helloworld"] 

my_list.insert(1,"happyDay")

print(my_list)

["helloworld","happyDay"]

 

6)Append operation:

append operation inserts the element at the end of the list.

my_list.append("happyCoding") 

print(my_list)

["helloworld","happyDay","happyCoding"] 

 

Deleting list elements 

  • pop

  • delete

  • remove

my_list=["helloworld","happyDay","happyCoding"]

 

7)Pop opertion:

my_list.pop()

output:  happyCoding   (removes last element)

my_list.pop(0)

output:  helloworld    (when mentioned an index, removes element in that particular index)

Now,my_list has only one element in it.

my_list=["happyDay"]

 

8)Remove:

my_list.remove("happyDay")   //removes 1st occurance of that string

My my_list is empty.

print(my_list)

[]    output - an empty list.

 

9)Delete operation:

del(my_list) output - deletes the memory address of the list.

 

10)Copy: 

my_new_list=my_list.copy() output - copies elements in my_list to my_new_list

 

11)Count: 

my_list.count("element") output -returns count of specified element in my_list. 

 

 

No comments:

Post a Comment

Anaconda Installation

In this post we will discuss about Anaconda and its installation. Anaconda comes with number of applications(jupyter notebook included), dat...