Original Source Here
smart and simple
Forget about all the definitions just keep in mind that the list is the same as arrays in c,cpp, java but more powerful than those.
- what we are going to learn:
2. Indexing and Slicing
4. When to use in Application
The list is heterogeneous in nature which means we can have different types of data in a single list. for example my_list = [10, 20, 30 , ‘Mumbai’]
- Always remember that everything in python is an object. Even class is also an object.
Ok so let’s learn about mutability
let’s take an example,
python will create object 10 for i variable but for j python is very smart, it will check that is there any object in RAM which is 10 if yes then j will simply refer to that object. If you print id(i), id(j) both will be at the same location
Here you can see when we are changing the value of i to 20, python will check in RAM if there 20 present or not if not it will create a new object of 20 and now i will refer to that 20 object. which means we are not overwriting 10, we are creating a new object. This is known as immutability. so we can say that int is immutable.
let’s see in the case of the list:
The object of the list will get created in RAM and that object will store references of elements. i.e 10 20 and 30
Now you can see that after changing the value of my_list, the id(id is nothing but location of the object in RAM) is not going to change, only the reference of an object will change, that’s why we can say that List is mutable. Now we can say that we can change the values of the list.
You can simply print list: print(my_list), but if you want to access elements one by one, you can iterate through the list
range is a generator, which gives us values according to the data which we have provided.syntax : range(start,end,step)for i in range(10,15,1):
ouput:10 20 30 40remember end is exclusive that means loop will stop before 15.
by default step size is 1
______________________________#here step size is 2
for i in range(10,20,2):
output : 10 12 14 16 18
______________________________#step size is -2
for i in range(20,10,-2):
output : 20 18 16 14 12
______________________________# by default start will be 0 and step will be 1
for i in range(5):
output:0 1 2 3 4
let’s print elements of the list
#by using for loopfor i in range(my_list):
print(i)#here i will directly point to the element in list,#by using while loopi = 0
while i < len(my_list):
#len is inbuild function to calculate length
stay tuned we will share more about lists……
Trending AI/ML Article Identified & Digested via Granola by Ramsey Elbasheer; a Machine-Driven RSS Bot