Python Basics – Print, Data types and comments

List / Array in python programming

As you have seen so far each variable can contain and single item in them. What if we have 5 variables and want to use them in a single one instead of declaring it 5 different times. Programming is suppose to make life easier not difficult right? Yep lets do it.

List or an Array as we call it is a collection of variables stored inside them. Lists are declared the same way as a normal variable but is different when we put values inside it.

shopping = [“Milk”, “Bread”, “Tea”, “Coffee”, “Biscuit”]

Can you spot the difference. We are using the square brackets which is on the right side of P key of the keyboard. Everything inside this square bracket will be seen as a single variable and we can access it all the time.

print(shopping)

This will return all the values stored inside that list.
Interesting thing about lists or arrays in python is the way it counts them. There are 5 different values in that shopping array its simple counting right 1, 2, 3, 4, 5. We will try to access each item individually.

print(shopping[1])

This will return the value Bread. We know that’s not the first thing on the list but why? Arrays start counting from 0 upwards they don’t start counting from 1. So try this now

print(shopping[0])

To check the length of the array or to put it simply, if you want check how many items are present in the current array you can do that by:

print(shopping.__len__())

This will display 5. It counts from 0 but it still counts as number so its 5 all together. This will return the value Milk. Try the other values, to make sure its all accessible. If we want to add an item to the array we can do that lets try this

shopping.append(“Beans”)
print(shopping.__len__())

This will return 6. Because we just added beans to the list by using the append function. Append function is used to add a value to the existing array. We use it like this

shopping.append() # add any values inside to be added to the original array

So where did we add the beans to? Each item in the array has a order right, when we added the beans to the shopping list it went all the way in back of the list.

print(shopping[5])

Lets remove Tea from the shopping list. We have some at home and don’t need it this week.

shopping.remove(“Tea”)
print(shopping.__len__())
print(shopping)

This will return the value 5 instead of 6 and you will see that it has removed tea from the list. Pretty cool right.




Comments are closed.

%d bloggers like this: