Press "Enter" to skip to content

Python List

Zigya Acadmey 0

The list is a data structure in Python which contains a mutable, ordered sequence of elements.

Declaring a variable of the List Type:

The syntax for list :<variableName> = []. And inside these square brackets, we add the values we want separated by commas. The following example will make things clear.

myList = [1, 2, 3, 4, 5] #This is list
print(type(myList))

We can store any type of value inside a list. For example, we can store a list of strings. Or we can create a list with both numbers and strings. Or we can even have a list inside a list.

myList2 = ["Hello", "This", "Is", "A", "List"]
myList3 = ["A", "List", "can also contain numbers", 1, 2, 2.2]
print(type(myList2))
print(type(myList3))

You can combine two lists by using the + sign:

myList = [1, 2, 3]
myList2 = [4, 5]
myList3 = myList + myList2

So now myList3 will contain [1, 2, 3, 4, 5] . Same goes for lists consisting of a combination of multiple data types. It just adds the list to the right of the + operator to the list on the left of the + operator.

Accessing elements in the list:

Because Lists are an ordered sequence of data items we can index them. Just like in Strings. You can access elements inside the list using a method called Indexing. Meaning every data item in the list has a number associated with it. Using these numbers we can grab parts of the list and we can manipulate them without affecting the original List. All you have to do is pass in the position of the element you want to access to the list. It is important to note that the position of elements in a list of any data type that is indexable starts with 0. Let’s look at an example.

myList = [1, 3, "Four", 5, "Six", 7]

A List can be indexed in two ways:

  1. Positive Indexing
  2. Negative or reverse indexing

1. Positive Indexing:

In positive indexing, the list is numbered from left to right starting with 0. Yes 0. You start numbering from 0. So 0 will the index value of the first data item in the list, 1 will be the index value of the second item in the list and so on …

2. Negative Indexing:

In negative indexing, the list is numbered from the right to left start with negative 1. So -1 will the be the index of the first item from the right and you increment as you go on …

So to grab a data item from the list:

Syntax : listName[index]

a = myList[0]  # stores 1 in a 
b = myList[5]  # stores 7 in b
c = myList[-1] # stores 7 in c
d = myList[-2] # stores 'Six' in d

Accessing elements in the list using Slicing:

Using slicing we can use indexing to grab multiple items of the list. Here’s the Syntax : listName[startIndex : stopIndex].

The stop index is excluding meaning it’ll grab the items only until the stop index but not including the character at the stop index. The start index is inclusive of the item at the start index. Run the code below.

Adding elements to the list:

Now if we want to add elements to the list we can use the methods append(), insert() and extend().

  1. append():

Using append we can add a single element at the end of the list.
In the append() method you simply pass the element to it.

We’ll learn more about what passing means when we learn about functions in python. For now think of it as sending something to this line of code which in-turn makes use of some other lines of code which python knows by default.

If it is just numbers you don’t have to bother about the ‘’ . If it is a character or a string you must enclose it in a ‘’ or “”.

myList = [1]
myList.append(2)

2. insert():

Using the insert() method we can add elements at a specific index in the list.
In the insert() method we pass in the index (position) we want to add the element followed by the actual element. This will add the element at the specified index pushing the other elements in the list towards the right.

myList1 = [1, 3, 4, 5]
myList1.insert(1, 2)

3. extend():

In the extend() method we need to pass the elements to it as another list (in [] separated by commas).

myList2 = ["Hello"]
myList2.extend(["World", "!"])

If you just pass in using ‘’ or “” it’ll add each character of the element as a new item on the list you are performing the method on.

myList3 = ['H', 'E', 'L']
myList3.extend('LO')

Deleting elements from the list:

Now if we want to delete elements from the list we can use the pop()del() or the remove() methods.

  1. pop():

The pop() method will remove a single element from the end of the list each time it is used. You can optionally pass the index to the pop() method to delete elements at a particular index.

myList = [1, 2, 2, 3, 4, 5, 5]
myList.pop()

2. del():

Using the del() method we can delete an element at a specific index. You need to pass the index of the element you want to delete to it. The del() syntax is a little different. We use del Listname[index]. The only difference between del() and pop() is that pop() returns the element that is being deleted while the del() does not.

del myList[5]

3. remove():

And using the remove() we can remove the first occurrence of the element in the list. Meaning if the list1 has [1,2,3,2,4] using remove(2) on it deletes the 2 at index 1 and not the one index 3 as well. It stops after deleting the first occurrence the element you pass to it.

myList.remove(2)

Bonus operations on List:

There are a few additional useful methods that you can apply to Lists such as sort() and  reverse().

  1. sort():

If your list consists of numbers you can use the sort method to store the numbers in the list in ascending or descending order. Same goes for strings in the list(based on the first character of the string). This ascending/descending order is dependent on the actual values of the elements in the list. For descending order alone we need to pass something a little special to the method. We need to pass reverse = True to the sort() method for descending.

myList = [1, 4, 8, 9, 3]
myList.sort()
myList.sort(reverse = True)
myList1 = ['a', 'z', 'y', 'e', 'b']
myList1.sort()
myList1.sort(reverse = True)

2. reverse():

As the name suggests, it is used to reverse the elements in the list but based on the index and not on the actual values.

myList2 = [1, 3, 2, 5, 6]
myList2.reverse()

Conclusion

In this article we learned about the List Data Type, how to declare it, add lists together, indexing, slicing and it’s madness. We learnt some useful methods that we can apply on Lists as well.

This brings the end of this Blog. We really appreciate your time.

Hope you liked it.

Do visit our page www.zigya.com/blog for more informative blogs on Data Science

Keep Reading! Cheers!

Zigya Academy
BEING RELEVANT

Leave a Reply

Your email address will not be published. Required fields are marked *