lists
lists
Introduction :
List is a collection of elements which is ordered and changeable (mutable).
Allows duplicate values of different types separated by commas and enclosed within square
brackets ([ ]).
Difference between list and string:
List String
Mutable Immutable
Element can be assigned at specified Element/character cannot be
index assigned at specified index.
Example: Example:
Syntax:
Example:
Accessing lists:
The values stored in a list can be accessed using the slice operator ([ ] and [:])
with indexes.
List-name[start:end:skip] will give you elements between indices start to end-1.
The first item in the list has the index zero (0).
Example:
>>> number=[12,56,87,45,23,97,56,27]
Forward Index
0 1 2 3 4 5 6 7
12 56 87 45 23 97 56 27
-8 -7 -6 -5 -4 -3 -2 -1
Backward Index
>>> number[2]
87
>>> number[-1]
27
Traversing a LIST:
Traversing means accessing and processing each element by using for loop.
Example:
>>> day=list(input("Enter elements :"))
Enter elements : sunday
>>> for d in day:
print(d)
Output:
s
u
n
d
a
y
List Operators:
Joining operator +
Repetition operator *
Slice operator [:]
Comparison Operator <, <=, >, >=, ==, !=
>>> L1=['a',56,7.8]
>>> L2=['b','&',6]
>>> L3=[67,'f','p']
>>> L1+L2+L3
Example:
>>> L1*3
>>> 3*L1
Slice Operator:
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:-2]
List-name[start:end:step] will give you elements between indices start to end-1 with
skipping elements as per the value of step.
>>> number[1:6:2]
[27, 56, 97, 23, 45, 87, 56, 12] #reverses the list
>>> number=[12,56,87,45,23,97,56,27]
>>> number[2:4]=["hello","python"]
>>> number
List functions:-