Skip to main content

Python : List and related functions



List is a datatype in python which can store a set of values.
Lets say we need to create a list as 'name'

Initialize a list
name = list()

Alternate way is
name = [] #This will make an empty list
name = ['apple','orange','mango'] #This will make a list with 3 elements

Various functions that can be performed on list

APPEND(element)
Adds an element to the list

>>> name = ['apple','orange','mango']
>>> name.append('banana')
>>>['apple','orange','mango','banana']

EXTEND(list)
This function can be used to merge two or more list into one.
lets says we have another list fruits = ['coconut','jackfruit']

>>> name = ['apple','orange','mango']
>>> name.extend(fruits)
>>>['apple','orange','mango','coconut','jackfruit']

INSERT(position,element)
To insert an element at specified location

>>> name = ['apple','orange','mango']
>>> name.insert(2,1)
>>>['apple','orange',2,'mango']

REMOVE(element)
Remove the first occurrence of the element specified from the list

>>> name = ['apple','orange','mango']
>>> name.remove('orange')
>>>['apple','mango']

POP()
This removes the last element from the list

>>> name = ['apple','orange','mango']
>>> name.pop()
>>>['apple','orange']

INDEX(element)
This returns the index of the element specified (first occurrence)

>>> name = ['apple','orange','mango']
>>> name('apple')
>>>0


COUNT(element)
This returns the count of occurrences of the element specified in the list

>>> name = ['apple','orange','mango']
>>> name.count('apple')
>>>1

SORT()
This function will sort the list

>>> name = ['apple','orange','mango']
>>> name.sort()
>>>['apple','mango','orange']

REVERSE()
This function will reverse the list

>>> name = ['apple','orange','mango']
>>> name.reverse()
>>>['mango','orange','apple']



Comments

Popular posts from this blog

UNIX : How to get record count from zipped file

Sometimes we may need to get records count from file . For that we can use wc -l , command with file name. In some situation the file will be in compressed format . wc -l will not directly work with zipped files . In this case we can do zcat the file and pipe the word count command with it. Example : Let say we have a file cricketData.dat.gz To get word count from the file use : zcat cricketData.dat.gz | wc -l This will give the record count.

Excel : How to pad zeros

Today I got a requirement to format the number in excel cell - to left pad number with zeros.i find the following function very useful to do it. In case one to make the number left padded with "0" s give the formula =TEXT(A1,"0000") In case two even more enhanced form to make it left padded with "0" and add two decimal places give the formula as =TEXT(A2,"0000.00")

Scala

Scala is a object oriented functional type programing language. All variables declared in scala is considered as objects.