September
26
Lists
List is a sequential data type. List values are comma separated and enclose with square bracket.
List in Python is like array in Perl and an array(ArrayList Class) in Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
>>> >>> tmp_list = ["a", "b", "z"] # Defining Lists >>> tmp_list ['a', 'b', 'z'] >>> tmp_list [0] # accessing element of list 'a' >>> li[2] 'z' >>> tmp_list[4] # try to read or write an element that does not exist, gives an IndexError Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> tmp_list[4] IndexError: list index out of range >>> dir(tmp_list) # dir will list-out all attributes of object ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] |
Key features of List:
- List items can be any datatype, within a single list you can have multiple datatype as item
- List can have duplicate values
- List is Mutable object
- Negative index access value from end of the list i.e. tmp_list[n-1] = tmp_list[-1]
- You can use any integer expression for index
Adding items to list, you can insert item to any place in the list using insert method. append method will insert item at the end.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
>>> >>> li = ['a', 'b', 'c'] >>> li.append('d') >>> li ['a', 'b', 'c', 'd'] >>> li.insert(1,'x') >>> li ['a', 'x', 'b', 'c'] >>> li.insert(-1,'y') >>> li ['a', 'x', 'b', 'y', 'c'] >>> li.append([1,2]) # you can add list as an item >>> li ['a', 'x', 'b', 'y', 'c', [1, 2]] |
List has extend and append method,both add values to list but both work differently.
Extend takes single argument,which is always list whereas append can n number of argument and add each item to original list.