DevScript Saga

Welcome to DevScript Saga!

A little Helping Hand for Devs

In this tutorial , we will discuss Python lists.

 Lists

The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type. Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on.

Basic List Operations:

Python ExpressionResultsDescription
len([1, 2, 3])3Length
[1, 2, 3] + [4, 5, 6][1, 2, 3, 4, 5, 6]Concatenation
[‘Hi!’] * 4[‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’]Repetition
3 in [1, 2, 3]TrueMembership
for x in [1, 2, 3]: print x,1 2 3Iteration

Indexing, Slicing, and Matrices:

Consider example:
L = ['python', 'Python', 'PYTHON!']
Python ExpressionResultsDescription
L[2] PYTHON !Offsets start at zero
L[-2] Python Negative: count from the right
L[1:][‘ Python ‘, ‘ PYTHON !’]Slicing fetches sections

Built-in List Functions & Methods

Python includes the following list functions −

Sr.No.Function with Description
1cmp(list1, list2) -Compares elements of both lists.
2len(list) -Gives the total length of the list.
3max(list) -Returns item from the list with max value.
4min(list ) -Returns item from the list with min value.
5list(seq) -Converts a tuple into list.

Python includes following list methods:

Sr.No.Methods with Description
1list.append(obj) -Appends object obj to list
2list.count(obj) -Returns count of how many times obj occurs in list
3list.extend(seq) -Appends the contents of seq to list
4list.index(obj) -Returns the lowest index in list that obj appears
5list.insert(index, obj) -Inserts object obj into list at offset index
6list.pop(obj=list[-1]) -Removes and returns last object or obj from list
7list.remove(obj) -Removes object obj from list
8list.reverse() -Reverses objects of list in place
9list.sort([func]) -Sorts objects of list, use compare func if given
 Today's Assignment:
 1.Write a Python program to get the difference between the two lists. 
2. Write a Python program to remove duplicates from a list. 
3. Write a Python program to count the number of strings where the string length is 2or more and the first and last character are same from a given list of strings.
4.Write a Python program to sum all the items in a list. 
5.Write a Python program to find the second largest number in a list 
6.Write a Python program to convert a pair of values into a sorted unique array 
Click here For Solution...

For more practice examples , you can download the book here….

Visit Downloads page too for more stuff….

Leave a comment