Friday, March 9, 2012

More List Functions

In this post, I will show some more functions about lists

So as usual, open up the IDLE, and then let us create a list

>>> python = [3,5,1,75,35,0,45]
>>>

So here we created a list named "python" now we will work with this list.

First we will see how to find the length of a given list

Syntax: len(listname)

>>> len(python)
7
>>>

Ok here we have seen it replied that there are 7 elements in the list 'python'

Next, we will see how to find the biggest number in a given list

Syntax: max(listname)

>>> max(python)
75
>>>

Next we will see how to find the smallest number in a given list.

Syntax: min(listname)

>>> min(python)
0
>>>

So it returned '0' because the smallest number is 0 in the list

Next, we will see how to replace any particular element of a given list.

Syntax: listname[index_number of the element to be changed] = replace with number

>>> python
[3, 5, 1, 75, 35, 0, 45]
>>> python[4]=165
>>> python
[3, 5, 1, 75, 165, 0, 45]
>>>

Okay here 35 was was on the index number 4, and we replaced it with 165.

Next, lets see how to delete a particular element of a given list.

Syntax: del listname[index number]

>>> python
[3, 5, 1, 75, 165, 0, 45]
>>> del python[5]
>>> python
[3, 5, 1, 75, 165, 45]
>>>

So we see that '0' has been deleted from the list

Okay here is one more important function, it converts a string to a list.

Syntax: list(String)

>>> name = "Python"
>>> list(name)
['P', 'y', 't', 'h', 'o', 'n']
>>> list('Programming')
['P', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g']
>>>

Now here I wil just show a summary of the functions that we learnt here.

>>> name = "Python"
>>> list(name)
['P', 'y', 't', 'h', 'o', 'n']
>>> list('Programming')
['P', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'i', 'n', 'g']
>>> array = list(name)
>>> array
['P', 'y', 't', 'h', 'o', 'n']
>>> len(array)
6
>>> del array[5]
>>> array
['P', 'y', 't', 'h', 'o']
>>> array[4]='m'
>>> array
['P', 'y', 't', 'h', 'm']
>>> name
'Python'
>>>

Okay, I hope This was informative and clear

Here is a task for you, make a list of numbers and show the use of all the functions that has been discussed.

Thank You.

2 comments:

  1. >>> Num="95463128"
    >>> Listed = list(Num)
    >>> Listed
    ['9', '5', '4', '6', '3', '1', '2', '8']
    >>> len(Listed)
    8
    >>> del Listed[5]
    >>> Listed
    ['9', '5', '4', '6', '3', '2', '8']
    >>> Listed[5]='Me'
    >>> Listed
    ['9', '5', '4', '6', '3', 'Me', '8']
    >>> min(Listed)
    '3'
    >>> Num
    '95463128'
    >>>

    ===========================

    thanks bro :)

    ReplyDelete