Python – List:
Python Lists holds the data of any datatype like an array of elements and these are mutable means the possibility of changing the content or data in it.
List can be created by giving the values that are separated by commas and enclosed in square brackets. Let us see different types of value assignments to a list.
Example:
List1=[10,20,30,40,50]; List2=['A','B','C','D']; List3=[10.1,11.2,12.3]; List4=['html','java','oracle']; List5=['html',10.1,10,'A'];
As we know the way strings can be accessed, same way Lists can be accessed. Below is example of indexing in python for your understanding again.
Example:
List1=[10,20,30,40,50];
0 1 2 3 4 ---> Forward Indexing -5 -4 -3 -2 -1 ---> Backward Indexing
Accessing and slicing the elements in List
Now let us take a list which holds different datatypes and will access the elements in that list.
Example:
>>> list5=['html',10.1,10,'A']; >>> list5[0] 'html' >>> list5[1:2]; [10.1] >>> list5[-2:-1]; [10] >>> list5[:-1]; ['html', 10.1, 10] >>> list5[:-2]; ['html', 10.1] >>> list5[1:-2]; [10.1] >>> list5[1:-1]; [10.1, 10] >>> list5[-1]; 'A' >>> list5[3:]; ['A'] Using Functions with Lists: Example: >>> list5=['html',10.1,10,'A']; >>>len(list5) 4 >>> 10 in list5 True >>> 'html' in list5 True >>>num=[10,20,30,40]; >>> sum(num) 100 >>> max(num) 40 >>> min(num) 10
Checking if the Lists are mutable:
Example:
>>> score=[10,20,30,80,50] >>> score [10, 20, 30, 80, 50] >>>score[3]=40 >>> score [10, 20, 30, 40, 50]
List Comprehension:
List comprehension works like iterate operations as mentioned below.
Syntax:
[x for x in iterable]
Example:
>>>var=[x for x in range(5)]; >>>var [0, 1, 2, 3, 4] >>>var=[x+1 for x in range(5)]; >>>var [1, 2, 3, 4, 5] >>>var=[x for x in range(5) if x%3==0]; >>>var [0, 3]
Adding Elements to a list:
We can add two lists as shown in the below example.
Example:
>>> var1=[10,20] >>> var2=[30,40] >>> var3=var1+var2 >>> var3 [10, 20, 30, 40]
Replicating elements in Lists:
we can replicate elements in lists as shown in the below example.
Example:
>>> var1*2 [10, 20, 10,20] >>> var1*3 [10, 20, 10, 20, 10, 20] >>> var1*4 [10, 20, 10, 20, 10, 20, 10, 20]
Appending elements in Lists:
We can append an element to an existing list as shown in the below example.
Example:
>>> var1.append(30) >>> var1 [10, 20, 30] >>> var1.append(40) >>> var1 [10, 20, 30, 40] >>> var2 [30, 40]