One of the basic data structures in Python is sequences. There are six built-in types of sequence - strings, Unicode strings, lists, tuples, buffers, and xrange objects. The most common are lists and tuples.
A list is an ordered set of values, where each value is identified by an index. The values in the list are known as elements. Each element of a sequence is assigned with a number - its position or index. The first index is zero, second is one and so forth.
Creation and Accessing List:
The list can be created by putting values separated by commas between square brackets []. List is one of the most freuently used and very versatile data type used in Python.
Syntax for List:
<List_name> = [<Value_1>,<Value_2>,........,<Value_N>]
NOTE: Nested lists are also acceptable.
List Operations:
Two operations + and * is allowed in list. + for concatenation of lists and * repeats the list elements a given number of times.
Try Yourself:
Nos_List = [1,2,3]
Char_List = ["a","b"]
#add two lists
Add_list = Nos_list + Char_List
#Append same elements n no.of times
Repeat_List = Char_List * 3
print "Add_List : ", Add_List
print "Repeat_List : ", Repeat_List
List Slices:
A subsets of elements of a list is known as slice of list. Selecting a list slice is similar to selecting a character in a string.
Try Yourself:
Nos_list = [1,2,3,4,5,6,7,8,9,10,11]
#different slicing of list
print "Elements 3rd to 5th : ", Nos_list[2:5]
print " Elements beginning up to -5th index : ", Nos_list[:-5]
print "Elements from 5th to end : ", Nos_list[5:]
print "Elements from beginning to end : ", Nos_list[:]
List Methods:
The list datatypes has some methods. Methods that are available for the list object in Python Programming are tabulated as follows:
The following table gives the result of every method for the considered list. in general the methods are accessed as ListVariable.MethodName().
List Slices:
A subsets of elements of a list is known as slice of list. Selecting a list slice is similar to selecting a character in a string.
Try Yourself:
Nos_list = [1,2,3,4,5,6,7,8,9,10,11]
#different slicing of list
print "Elements 3rd to 5th : ", Nos_list[2:5]
print " Elements beginning up to -5th index : ", Nos_list[:-5]
print "Elements from 5th to end : ", Nos_list[5:]
print "Elements from beginning to end : ", Nos_list[:]
List Methods:
The list datatypes has some methods. Methods that are available for the list object in Python Programming are tabulated as follows:
The following table gives the result of every method for the considered list. in general the methods are accessed as ListVariable.MethodName().
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Leave your comments for any future suggestions..
ReplyDelete