Ok! So lets talk about lists in Python.
Lists is one of the type of python objects. I have talked about python classes,objects and methods here. I will just explain about it here briefly:
Briefly everything in python is an object. And an object is of different type(like: list, string, float, numpy array). So list is just one of the type of python object.
Lists is one of the type of python objects. I have talked about python classes,objects and methods here. I will just explain about it here briefly:
Briefly everything in python is an object. And an object is of different type(like: list, string, float, numpy array). So list is just one of the type of python object.
INITIALIZATION of a List
lets initialize a variable x to a list:
x = [1,"Rahul",2,"Ram",3]
Note that, a list can contain different types as well(here,1 is an int while "rahul" is a string).
lets take a look at list of lists:
y = [["liz",1.73],["emma",2.68]]
We can see the type by using type() function:
type(x) OR type(y)
this gives list as python object type.
SLICING of a List
To select first element of a list:
x[0]
gives 1.
Remember: Indexing starts from 0 in python. So here, index of 1 is 0.
index of "Rahul" is 1. and so on.
Also, Index of last element is -1
Index of 2nd last element is -2 . and so on.
To select multiple elements of the list:
x[1 : 4]
gives ["Rahul",2,""Ram"]
NOTE THAT: element at index 4 is excluded.
Doing this: x[1 : ]
gives ["Rahul",2,"Ram",3]
Similarly, x[: 2]
gives [1,"Rahul"]
For Lists of list
y[0] gives ["liz",1.73]
To select "liz":
y[0][0] gives "liz"
To select 2.68:
y[1][1] gives 2.68
Comments
Post a Comment