A list is a way to store data. In languages like C, php we saw they use a special type of variable called an array. In python we call them lists. Both of lists and arrays do the same.
In following program we make a list with the name "Langs". Lists use indexed method to extract data.
Thilan@ubuntu:~/programming$ cat tmp1.py
#!/usr/bin/env python
Langs =['python', 'ruby' , 'pearl' , 'C' , 'VB' , 'assembly' , 'php']
print(Langs[2])
print(Langs[0])
print(Langs[1])
#we can modify a value too.
Langs[2] = 'JavaScript'
print(Langs[2])
#hear we add something to end of list
Langs.append('Java')
print(Langs[7])
#get the length of a list
print ("length is %d"% (len(Langs)))
Thilan@ubuntu:~/programming$ python tmp1.py
pearl
python
ruby
JavaScript
Java
length is 8
Thilan@ubuntu:~/programming$ python3 tmp1.py
pearl
python
ruby
JavaScript
Java
length is 8
As the first step we created a list. Following syntax is used to it
list_name =['item1', 'item2' , 'item3' , ......, 'itemn']
Next we can get elements from it.
list_name[n-1] will give us element n.
In above example we can see that when we use Langs[2] it printed 'Pearl' while Langs[0] printed 'Python'. That means If we want to access first element we use index 0. Because indexing of a list starts with zero.
We can modify a list item with following method.
Langs[2] = 'JavaScript'
After that code line I examined Langs[2] again. It changed from pearl to JavaScript.
Also we can add an item to the end of the list using append method.
Finally I have mentioned about length() function. It will return the length of the list. That means we get number of items in list.
Next we have an example for a dictionary . There are not any complex thing hear. I think you can clearly understand what is going hear.
Thilan@ubuntu:~/programming$ cat tmp1.py
#!/usr/bin/env python
mySelf = {'name': 'Thilan', 'country' : 'SriLanka' , 'age': 21, 'study':'Computer engineering'}
# now we can get the data we want from it.
print (mySelf['age'])
#why not use them with format strings?
print ('I\'m %s and %s years old.' %( mySelf['name'] , mySelf['age']))
Thilan@ubuntu:~/programming$ python tmp1.py
21
I'm Thilan and 21 years old.
Thilan@ubuntu:~/programming$ python3 tmp1.py
21
I'm Thilan and 21 years old.
It's working with both versions. Now you want to combine this concept with other theories we learned.