Lists are Python’s most flexible ordered collection object type. A list can be created by putting the value inside the square bracket and values are separated by comma.
<list name>=[value1,value2,...,value n];
Unlike strings, lists can contain any sort of object: numbers, strings, even other lists. Python lists are:
- Ordered collections of arbitrary objects
- Accessed by offset
- Arrays of object references
- Variable length, heterogeneous, arbitrarily nestable
- Of the category mutable sequence
- The elements are stored in the index basis with starting index as 0.
- A python list is enclosed between square() brackets.
list1 = [1,2,3,4,5]; list2=["hello","intellipaat"];
To access list following syntax is used:
list1 = [1,2,3,4,5];
Operations on List
On list following operation are performed:
- Concatenate List
+ Operator is used to concatenate two lists.
L1 = [1, 2, 3, 4] L2 = [5, 6, 7, 8] print L1+L2
[1, 2, 3, 4, 5, 6, 7, 8]
- Replicate Lists
Operator * is used to repeat a list by specific number of time.
L1=[1,2] print L1*2
[1,2, 1, 2]
- Sub List
It is used to obtain a sub list which is done by specifying the index.
L1 = [1,2,3,4] print L1[0:3]
[1, 2, 3]
- Update List
For this purpose assign the value to the index of the list.
L1 = [1, 2, 3, 4] L1 = 0 print L1
[0, 2, 3, 4]
To delete value from list del is used.
L1 = [1, 2, 3, 4] del L1 print L1
[2, 3, 4]
Functions and Methods in List
|min(list_name)||Returns the minimum value from the list|
|max(list_name)||Returns the largest value from the list.|
|len(list_name)||Returns number of elements in a list.|
|cmp(list1,list2)||Compares the two lists.|
|list.reverse()||Reverse the list|
|list.sort||Sort the list|
|list(sequence)||Covert the sequence into the list|
|list.append(value)||Add the value into the list|
|list.remove(value)||Remove the value from the list|