Lists in Python 3:
Lists are the most versatile of Python's compound data types. A list
contains items separated by commas and enclosed within square brackets ([]). To some
extent, lists are similar to arrays in C. One of the differences between them
is that all the items belonging to a list can be of different data type.
The values stored in a list can be accessed using the slice operator
([ ] and [:]) with indexes starting at 0 in the beginning of the list and working their
way to end -1. The plus (+) sign is the list concatenation operator, and the
asterisk (*) is the repetition operator.For example-
- Lists are in square brackets -- [ ]
- Different data types can be in a List.
- Slicing operators are -- [ ] and [:]
- indexes starts from 0 in forward direction and -1 in reveres direction.
- Concatenation operator is + sign
- Repetitive operator is * sign.
Lets' see an example. file name : list.py
Updating Lists
You can update single or multiple elements
of lists by giving the slice on the left-hand side of the assignment operator,
and you can add to elements in a list with the append() method. For example-
#!/usr/bin/python3
list = ['science', 'english', 9741, 1000]
print ("Value available at index 2 : ", list[2])
list[2] = 1001
print ("New value available at index 2 : ", list[2])
|
Note: The append() method is discussed
in the subsequent section.
When the above code is executed, it
produces the following result –
Value available at index 2 :
9741
New value available at index 2 :
1001
|
Delete List Elements
To remove a list element, you can use
either the del statement if you know exactly
which element(s) you are deleting. You can use
the remove() method if you do not know exactly which items to delete. For
example-
#!/usr/bin/python3
list = ['physics', 'chemistry', 1997, 2000]
print (list)
del list[2]
print ("After deleting value at index 2 : ", list)
|
When the above code is executed, it
produces the following result-
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 : ['physics', 'chemistry', 2000]
|
Note: remove() method is discussed in subsequent section.
Index Basic Lists Operations>>>