Python3 tutorial - 5 (Lists)

Python3 tutorial - 5

----------------------------------------------------------------------------------------------------------------

Hello and welcome to CCP and from here we will come across
som data structures which are very common in python3,
These are:
1. Lists -> []
2. Dictionaries -> {}
3. Tuples -> ()

list is defined like:
my_list = []
this list is an empty list and we can add elements into it by
the append() method, 
like this:
my_list.append("camel")
my_list.append("cases")
my_list.append("Python3")
my_list.append("I love it !")

when we will print the list, 
print(my_list)
it will show us like this:
["camel", "cases", "Python3", "I love it !"]
and we access its elements by number like this:

print(my_list[0]) # outputs -> camel
print(my_list[1]) # outputs -> cases

that is this because python counts elements from 0 and goes upto to 
(length of list) - 1,
we can find the length of list by the len() function,
like this:

print(len(my_list)) # outputs -> 4

we can access the last element of any list by 2 ways:
1. print(my_list[len(list) - 1]) # outputs -> I love it !
2. print(my_list[-1]) # outputs -> I love it !

we can like this only access the 2nd or 3rd element,
for example:
print(my_list[-2]) # outputs -> Python3
print(my_list[-3] # outputs -> cases

Iterating through the elements of a list:


Wait, what on the earth is that element and my_list doing with the for loop ?

this is the way how we iterate through each element of the list,
we declared the variable element which was followed by the in keyword and then came the name of the list we want for loop to iterate through,

python automatically puts the value of the specified variable each time we go through the variable and when the loop comes to end python again puts the value of another element in the list,

now, see this picture where we iterate through each element of the list and add the element to the sum variable,


here, we can clearly feel the advantage of for loop over which is widely used to iterate through a series of elements,
however, this same work can be done using while loop,
like this:


here, we declared a variable index and gave it a value of 0,
then, until the value of index is smaller than or equal to the length of my_list - 1 as the index is len(my_list) - 1 and then printed the value of my_list[index] and incremented the value of index by 1 using the increment operator +=,

we can see the difference b/w while and for loops when used to iterate through each element of the list,

I think you should now go and list things up and practice !

have fun coding and catch you later !

Comments