
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 Expression | Results | Description |
|---|---|---|
| len([1, 2, 3]) | 3 | Length |
| [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] | True | Membership |
| for x in [1, 2, 3]: print x, | 1 2 3 | Iteration |
Indexing, Slicing, and Matrices:
Consider example: L = ['python', 'Python', 'PYTHON!']
| Python Expression | Results | Description |
|---|---|---|
| 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 |
|---|---|
| 1 | cmp(list1, list2) -Compares elements of both lists. |
| 2 | len(list) -Gives the total length of the list. |
| 3 | max(list) -Returns item from the list with max value. |
| 4 | min(list ) -Returns item from the list with min value. |
| 5 | list(seq) -Converts a tuple into list. |
Python includes following list methods:
| Sr.No. | Methods with Description |
|---|---|
| 1 | list.append(obj) -Appends object obj to list |
| 2 | list.count(obj) -Returns count of how many times obj occurs in list |
| 3 | list.extend(seq) -Appends the contents of seq to list |
| 4 | list.index(obj) -Returns the lowest index in list that obj appears |
| 5 | list.insert(index, obj) -Inserts object obj into list at offset index |
| 6 | list.pop(obj=list[-1]) -Removes and returns last object or obj from list |
| 7 | list.remove(obj) -Removes object obj from list |
| 8 | list.reverse() -Reverses objects of list in place |
| 9 | list.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