Featured Post

BUILD A TODO LIST IN PYTHON

Image
Build a TODO List in Python Overview The objective is to build a todo list to which we can add items, remove the added items, edit the items and even if required, delete out the entire list itself. We will learn here step by step, how to build the todo list with the above  CRUD (Create, Remove, Update/edit, and Delete ) features.  This is a CRUD list  app  that we are building as we can Create, Remove, Update items in the list and Delete the entire list itself. We will be using Python3 to build this Project. Importing os and time We import time to let the screen pause for a while before clearing  and we import os to clear the screen . Initializing the list We initialize the todo list with an empty list as there are not items added yet to the list and this is represented in the code aby using an empty square braces   toDoList = [] Defining the print list  The def keyword is used to define a function in python. In the below code, we define the function called printList(). When we define

A Simple Guide to Python Lists

A Simple Guide to Python Lists



What are Lists 

Lists in Python are built-in data structures to store items in a specified order.

Lists store multiple items in a single variable. Sometimes, they could also be not carrying any item, that is, they could be empty as well. 

Let us delve deeper into the concept of lists, how they are created and what methods we can perform with lists.


Define Lists 

Lists are built-in data structures  in Python, that store multiple items with a specified order, in a single variable.


How to Create a List

To create a list, for example , below, we use a variable called names and store all strings, namely, "Jay", "Ann" and "Alan" using the square brackets and then we run the print command. We also consider another variable numbers storing numbers 1,2,3  as shown below.

  

names = ["Jay","Ann","Alan"] print(names)

numbers = [1,2,3]
print(numbers)




 



What are List Items

The list items could be of any data types, such as strings, integers or booleans. All instances of data types for the list items are demonstrated in the code below.


  

#string data type items
friends = ['Anny', 'Mary', 'Tom']

#integer data type items
count = [7,9,11,15]

#booleans data type items
fact = [True, False, True]

#mixed data type items

mixed = [1,2,7,True,False,"Cat", "Rose", "flower" ]




 


Modify / Mutate Items of a list 

Using index referencing we can modify the value of the item in a list
The list items are accessible by using their index references and as we know already, index for the first item  is always 0 and increases accordingly in this order. We could first access an item inside a list, like in the below example. We were able to run the print command for the names at index 0 that would print out the first item in the names list. We could also use the index reference with two parameters whereby, the first parameter is the index of the first item and the second parameter is the index at that index position and while accessing such an item in the list, remember that the item count starts from the first parameter and does not include the second parameter provided there. 
For example in the names[0:2] we start accessing from index position 0, which is the first item and then stops at index 1, that is one position lesser than the second parameter, 2. So, we would be left with the first item and second item in the accessed list. Now, if we allocate a name of 'Meera' to the second item with an index of 1, then run the print command for names, we find that the resultant list would have a modified list of items whereby "Meera" would replace the value of "Ann" in the names list. Hence the names list is modified. Similarly, we can explore further using different index positions for these parameters, including that of  -1 and as we already know, the value of -1 for an index would refer to the last item of the list as the index of a last item in a list is always -1
In the above code, names is an example of a list storing strings of different names, "Jay","Ann", and "Alan" respectively. When you run the print command, you will get the outcome with all these strings in a list. 
Outcome : ['Jay', 'Ann', 'Alan']
You can access any item in this list by referring to their index. This is how we can access the items in this list by referring to their index, let us do that for accessing the first item in this list, that is "jay". 
We use the square brackets that we normally use to indicate the index with the index number inside the square bracket, that will indicate the respective position of the item in the list.
Hence, as we want to access the first item of the list, obviously, we use the zero value inside the index bracket to indicate the first item  : names[0]
Now, if we run the print command, that is, write print(name[0]) then the outcome would be Jay which is the first item in the above list. Similarly, had we used the index value as 1 instead of 0, then, we would get the outcome of the print command as Ann as Ann is the second item in the list and the index value of the second item is always 1.
We can also slice this list by inserting two parameters inside the square brackets and when you use two values inside the braackets, then , remember , the slicing of the list starts from the first item and ends by excluding the very last item of the list. In this example, there are total three items in the name list,  and by running names[0,2] you can slice the list from the first item, Jay and ends at the second item Ann, as it cannot include the last item Alan. So, the final outcome on running the print command : print(names[0, 2]) would be ['Jay', 'Ann']
We can also modify values in the list, and let us see how it can be done here.
Let us assign a value of "Meera" to the second item by referring to names[1] and then when we run the print command for this list, we can see that the value of the item inside has been modified since now the second item in the list is Meera instead of Ann.



  


names = ["Jay","Ann","Alan"] print(names)
print(names[0]) print(names[0:2]) #modify values names[1] = "Meera" print(names) print(names[1])


friends = ["kay","May","Jay"] print(friends) print(friends[0]) print(friends[-1]) print(friends[0:]) print(friends[0:2]) #modify values friends[1] = "Mira" print(friends) print(friends[1])

 

Lists permit Duplicate Items


Lists can store items with duplicate values and when you run the print command for the below list num, you can see that the list retains all the duplicate values without ignoring a single one of the duplicate items at all.



  

num = [1,2,3,4,7,4,4] print(num)

#outcome
[1,2,3,4,7,4,4]


 

Determine the Length of a List


We can determine the length of a list by using the len() function. In the below example, the num list has a len of 7 since it has seven items, even though there are duplicate items inside, they are also taken into account while counting the number of items or rather the length of the list num.


  

num = [1,2,3,4,7,4,4] print(num)
print(len(num))

 



Data Types supported by Lists

Lists are able to store strings, integers and boolean data as shown below. It could either store alll of the strings or integers or booleans individually or a list could also have a mixed type of data, that is , a mix of various data types such as a mix of strings, booleans and integers.


  

#string, integer, boolean data

#string
names = ["Jay","Ann","Alan"]

#integer
num = [1,2,3,4,7,4,4]

#boolean
mylist = [True,False,True]





Determine the type() of a list 


By using the type() function, we can determine the type of the data of the list. In this case, using the type() function on mylist will give you the outcome of a class of 'list' , hence, you can safely say that mylist is a list.


  

mylist = [True,False,True] print(type(mylist))


#outcome

<class 'list'>



What is a List Constructor


We can use the list() constructor to make a new list. When we run the print command for mylist, we get a list with the items "Cats", "Dogs", Rabbits"," Mice" inside the square brackets!


  

mylist = list(("Cats", "Dogs", "Rabbits", "Mice"))
print(mylist)

#output

["Cats", "Dogs", "Rabbits", "Mice"]



Syntax 


List container is shown with a set of open and closed square brackets and in the following example we have a names variant storing three names, namely, Jay, Ann and Alan. These names are obviously string items contained in the names variant. 


Built-in List Methods


extend() 

The extend() method will add the particular list items specified to the end of the current or existing list.
We consider two other lists namely, friends and lucky_colors as shown in the code above. When we use the extend function, we are able to get both the values of the lists together in one list.  So if we want to add the items of the friends list and the lucky_colors list together , then we could use the .extend method like this : friends.extend(lucky_colors) and on running the print command on friends after this print(friends), we would get the outcome as ['Ann', Cathy', ' Preet,'  'red', 'pink,' 'blue'] 
So after using the extend method , the string items of the lucky_colors got added to the friends list.
Use the .extend() method, in the code below, we were able to add the list items of lucky_colors to the list items of friends.

append() 

Using the append() method, we can add an item to the end of the list. Please refer to the example code below using the .append() method. If we consider one of the lists, by the name of num containing integers, 2,4,8 and if we use the .append() method on num list, by using .append(1), we end up adding the integer 1 to the end of the num list as shown in the result of the code below.
Using the append method, you can also get all the string items from both the lists into one list, but, the items do not get added as individual items, instead as a list inside another list. For example, in this case, on performing the append method on friends, here is what happens:
friends.append(lucky_colors)  and their outcome would be a list of lucky_colors inside the list of friends 
Consider this outcome as explained above:
['Ann', 'Cathy', 'Preet', ['red', 'pink', 'blue']]
Now, if you use the append method again on friends list, then, it will get added to the friends list, but at the very end as seen:
friends.append("John")
print(friends)
['Ann', 'Cathy', 'Preet', ['red', 'pink', 'blue'], 'John']
You can continue adding more items to the friends list by using the append method but every time you append an item, it will get added to the very end of the list as shown in the below outcome:
friends.append("Jim")
print(friends)
outcome :
['Ann', 'Cathy', 'Preet', ['red', 'pink', 'blue'], 'John', 'Jim']

insert()

Using the insert() method we can add specified item to a specific position in the list and then, the rest of the items are shifted to the right of the added item in the list. In the example, using the insert() method, we add a number 6, at index 0 that is , the  first index position of the list.


remove()

The remove() method will remove the first occurrence of the item with a specified value and in case there are several instances of the items in the list, this method will only remove the first instance of the item specified, in case there are duplicate items available with the same value.
In the example code provided below, we see that in the list numbers, we have three numbers, 7,11, and 34 and when we specify the number 7 within the parenthesis of the .remove() method, then, the number 7 gets removed from the list and in the list mynumbers, we have numbers 9,12,45 and 70 in the list and the number 9 is repeated twice, once it occurs in the beginning of the list and then in the end of the list. When we use the remove method, then, only the number 9 that is at the first occurrence of the list , gets removed from the list and the second occurrence of the same number 9, repeated in the end of the list, does not get removed from the list.

pop() 

The pop() method will remove the item at the specified position.
In the following example below, we use the pop() method on mylist and specify the position of removing item as -1 and since the index of any last item in a list is -1, we find that in the result, the last result gets removed using the pop() method. Likewise, we can remove the item from any specified position accordingly as shown in more examples below. If we mention the index position within the round brackets of the pop() method, then we can delete the item at the specified position of the list , however, if we do not specify any index number within the round brackets of the pop() method, then, by default, the last item of the list gets removed from the list as shown in the example of using the pop() method on thislist.

reverse()

The reverse() method will reverse, as the name suggests, the sorting order of the items in the list.

We consider a list, myitems that stores the items, 'pencil', 'pen', 'paint', in this order and on performing the reverse() method, the myitem list would return the list with a reverse order of the items , that is, 'paint', 'pen', 'pencil' , in this order.


index()

The index () method will help us to access the item at a specified position , in the list that is containing it. For example, in the list myitems, if we want to access the item in the second position, we need to use the square brackets with the position mentioned. As we already know, the index of the first item is always 0 and increases in that order, that is, 0,1,2,3 and so on based on the item position and the index of the last item is always -1. In myitems list, the ite

sort()

The sort() method will arrange the items of the list in an ascending or increasing order, by default, unless, otherwise specified with the help of a function, that you will learn how to do , at a later stage of the Python lessons. We have considered a list by the name of mynum in the code editor shown below with numbers, 10,9,6,1 and after operating the sort method on the list, it will arrange these numbers in the increasing order and the result will be 1,8,9,10 as you can see, in this ascending order.


count()

The count () method will help to determine the number of times a particular item has occurrence in the list. For example , the list mynumbers has several numbers stored inside the list and when the count method is performed with the parameter 7, it will return a count of 4 since the number 7 has been repeated 4 times or rather occurred 4 times in the list.

copy()

This is another built-in method for making an exact copy of a list. If you see the example code provided below, the list original has numbers, 5,7,9 and we want to copy this list into another list by the name of mycopy. When you perform the copy method on the original list, you get mycopy which is exactly same as original.


list()

This method will also help to make  an exact duplicate copy of a list. In the example, we try to make another list , nextcopy, with same items from the list original. So, we use the list method by mentioning nextcopy = list(original) and the resultant list by the name of nextcopy will have the same items of the list original.


clear()

The clear method will remove or clear all the items from the list. It will return an empty list as shown in the example code below
You can also refer to this working example to fiddle around with the code syntaxes you just learnt to understand all about the list  methods in Python and  try practising to understand the code by exploring all the working examples that I have done below and also my source code



  

names = ["Jay","Ann","Alan"] print(names)
print(names[0]) print(names[0:2]) #modify values names[1] = "Meera" print(names) print(names[1])

#list functions friends = ["Ann","Cathy","Preet"] lucky_colors = ["red","pink","blue"] #print function print(friends) print(lucky_colors) #extend function #friends.extend(lucky_colors) print(friends) #append function friends.append(lucky_colors) print(friends) friends.append("John") print(friends) friends.append("jim") print(friends)


#append() method
num = [2,4,8]
num.append(1)
print(num)
#insert method num.insert(0,6) print(num)

#remove method numbers = [7,11,34] numbers.remove(7) print(numbers) mynumbers = [9,12,45,70,9,45] mynumbers.remove(9) print(mynumbers)



#pop method
thelist = [1,2,3,4,5,6,7] thelist.pop(-1) print(thelist) thislist = [5,9,10,13] thislist.pop() print(thislist)

#pop() method
mylist = [1,2,3,4,5,6,7] mylist.pop(-1) print(mylist)

myitems = ['pencil','pen','paint'] myitems.reverse() print(myitems)


#sort method
mynum = [10,9,6,1]
mynum.sort()
print(mynum)

#count method
mynumbers = [1,7,7,9,11,100,7,8,25,99,100,7]
y = mynumbers.count(7)
print(y)


#copy method
original = [5,7,9]
mycopy = original.copy()
print(mycopy)

#list method
original = [5,7,9]
nextcopy = list(original)
print(nextcopy)

#clear method
original.clear()
print(original)








Conclusion

We learnt a lot about lists in Python. To conclude, lists are built0in data types in Python that are used  to store multiple items in a single variable. Lists are expressed using square open and closed brackets. 

The items contained inside the list could be modified, and they are always arranged in an ordered manner with specific index positions whereby we can access various items in the list vide their index positions. Lists permit us to store duplicate values and we can perform several built-in methods as listed above with detailed steps and code.
Lists are able to accept various data types including strings, integers and booleans and also a mix of these data types. We have also identified different methods to create new list  as shown above. We are able to determine the length of a list using the len method and also the type of data using the type method.
In the coming lessons, we will learn all about Python Tuples.
Do let me know in the comment sections below, if you have any opinion to share about lists in Python.

You may also be interested in reading about Working with files in Python



 




Comments

Popular Posts

Build A Random Quote Machine in React

A Simple Guide to Promises in JavaScript ES6

Welcome to my first Blog Post

How To Fight Programmer's Imposter Syndrome

Top Free Online Websites to Learn Coding

Build A Calculator in React

Guide to Learn Coding Efficiently and Effectively