Skip to main content

python3 list: creation, addition, deletion

 Introduction:

Lists are one of the most fundamental data structures in python3.  In this article we are going to go through the basics and some of the advanced usage of lists in python and where should you use them and where you should not use them.

what is list?

List is a python data structure which is equivalent to a dynamic array in C++ or C. List is used to store normally homogeneous elements in python3; but pythons allow to store dissimilar elements in a list too. To say in summary, list is an ordered linear data structure.

How to create a list?

List can be created by using as simple as writing list = []; which initiates an empty list. Also, there is the list() builtin function in python which also creates a list. Empty lists can be created using both [] and list(); but it is known that [] is a bit faster method to initiate an empty list. 

List can also be created with the elements to be put into it. i.e. you can start a list with the elements it is supposed to have. For example, 

list = [1,2,3,4] initiates a list with all these elements 1,2,3 and 4. 

But in this case, writing list = list(1,2,3,4) does not work. we will explain the reason later; but for now; remember it doesn't work.

You can also create a list by entering elements one by one. For that you have to use append() method to add one element into a list. Let's see how to do one:

list_numbers = []

for i in range(10):

    list_numbers.append(i)

print(list_numbers)

In the above example, we create a list with elements from 0 to 9. 

Now, you may want to create a list out of some sets, arrays or some kind of iterables. In such a case, the list() function comes handy. For example:

import numpy

np_arr = np.array([1,2,3,4])

list_np_arr = list(np_arr)

Here, we have a np_arr as an array; and then using list() function we have converted it into a list. Similarly, we can create lists from sets and other iterables too.

List handling and manipulation:

Once the list is created, there are multiple manipulations you will want to do on it. Let's go one by one and explain with examples:

(1) finding out a list's length:

Often you will want to know what is the length of a list; and the len() method helps in doing that. let's say,

list = [1,2,3,4] is there. to know its length, you will use print(len(list)) which will print 4 in the console. It may come as a stupid thing in the begining, but the len() comes really handy while debugging programs involving lists; as lots of problems come with changing shapes of the data structures.

(2) adding elements to a list:

A list is a dynamic array in its build inside python. So the particular advantage is that you can add elements as you wish to the list. To add element at the end of a list, one can use the append option. For example,

list = ['you','are','learning'] and you want to append the string 'lists'; then you can achieve by list.append('lists'). Now if you print(list); then it will print

['you','are','learning','lists']

(3) accessing specific position of a list:

Now, you will want to get values at specific positions of a list. In order to do that; you have to provide the index of that value. i.e.

list = [1,2,3,4]

Now to access 1, you have to write print(list[0]). That will print 1. As you must have understood from the example, indexing in python lists start from 0. so basically in this specific example:

list[1] = 2, list[2] = 3, list[3] = 4.

Also, in case of lists in python, there is a way to access elements from the last too. i.e.

list[-1] = 4, list[-2] = 3 and so on. This specially helps when you don't know how long the list is, but want to access the last element or so on.

(3) taking a specific part of a list:

One of the not-so-intuitive thing about lists is that a part of a list is a full list again. And we often take advantage of it. We do, what we can call a slicing of a list, to create a sublist of it; just like you create substring from a string. A example of slicing is:

list = [1,2,3,4,5,6,7]

print(list[2:6])

>> [3,4,5,6]

so basically, list slicing is the process of breaking a list using a starting index and a ending index. The syntax is

list[starting_index: stopping_index] 

Observe that, this syntax includes the elements including starting index but excluding stopping index; i.e. list[stopping_index] will not come under the sublist we create in this way.

Also, one more important thing is, sometimes, you will want to print a list leaving some elements in the beginning. In such a case, you don't need to write the stopping index. In this case, you can follow this syntax:

list[starting_index:]

where it takes upto the end of the list in the sublist.

(4) inserting elements at a specific position:

Now, we already covered append. But problem with append is that it enters the element to the end of the list always. To enter elements at a specific position of a list; you need to use insert() method from a list. For example:

List_leaders = ['modi','tharur','rahul','mukesh'] is say a list of leaders.

Now, you want to enter "donald" just after modi, i.e. in position 1. To do that, you have to write

List_leaders.insert(1,'donald')

and voila! print(list_leaders) will show

['modi','donald','tharur','rahul','mukesh']

(5) extending a list by adding another list:

Now let's say you want to update the list in hand with a bulk of items; i.e. you want to add a number of elements to the existing list. There are two solutions to this. One is by using extend() method. The syntax for this is 

list.extend(iterable)

i.e. if you provide an iterable to the extend method as its parameter, the list will get updated with all the elements of the iterable at its end.

Another method is to directly add the lists using + and then storing the result in one of the lists. i.e.

list1 = list1+list2

Let's see both of these in the following example.

list1 = [1,2,3,6]

list2 = [3,8,5]

list1.extend(list2) 

print(list1)

>> [1,2,3,6,3,8,5]

list3 = list1+[2,4]

print(list3)

>>[1,2,3,6,3,8,5,2,4]

(6) The list comprehensions:

List comprehension is basically one of the most important tools to both create lists as well as for writing one-liner codes. Let's give an example first and you will understand.

list = []

for i in range(10):

    list.append(i)

creates the list containing integers from 0 to 9.

Now, using list comprehension this can be done in a line, see below:

list = [ i for i in range(10)]

so this is list-comprehension. It is the art of writing loops in one line inside a list, so that the result gets stored inside list. It is possible to put logic inside the comprehension too, upto the position when they are one line logics.

For example, if you want to store even numbers from 0 to 99 in a list, then you can just do this:

list = [i for i in range(100) if i$2 == 0]

clearly, it stores the even numbers in the list. 

you can even use a nested loop as long as one loop's range doesn't depend on another. For example,

list = [x+y for x in range(10) for y in range(10)] 

is equivalent to run:

list = []

for i in range(10):

    for j in range(10):

        print(i+j)

List comprehension, if practiced, saves a lot of nasty for loop writing while you get the same results. But also, you should be confident that the comprehension works correctly. i.e.

list = [1 for i in range(10)] creates a list containing 10 ,1s. So check what is it that you are actually storing in the list; which was 1 in this case.

(7) constant element lists:

For writing constant lists, i.e. lists which contains one specific number a few times; there is a short trick. The syntax is list_repeated = [elem]*length

i.e. list = [1]*5 creates [1,1,1,1,1]

This comes in handy when you want to initiate say a list of 0s. You can just do [0]*100 or whatever length you want the list to have.

(8) loop on a list:

It is often intended by a programmer to loop on a list. If you come from c or java background, you will go and write:

for i in range(len(list)):

    print(list[i]) 

to loop over all the elements of a list. But there is a more pythonic way, which is to loop on the list itself,i.e.

for elem in list:

     print(elem)

this loops on the actual list and prints the elements directly. This is again, more of a coding style and about what is pythonic to do about lists.

(9) sum and counts:

If you have a list of integers or floats, it is possible to sum the elements of the list, without actually looping through each of the items in the script. There is a sum() method for it, which helps to do it. For example,

list_specific = [1,2,3,4]

print(sum(list_specific))

>>10

Another important thing to understand is that list allows repeated values to be in it. So often one may want to count number of times one element occurs in the list. Again, you may want to loop over the list, and count it. But easier way to do it is using the list.count() method. For example,

list = [1,2,2,1,1]

print(list.count(1))

>>3

With this we reach to the end of list manipulation section. 

Now, the left part is list deletion.

Deletion:

There are three methods to delete a list item as par choice. The methods are pop(), del and remove. Let's see how each of them work.

list.pop(index) works by popping an element at a certain location of a list. This is important to note that, if you want to delete multiple items using indices, you will get into trouble. Because once list gets popped, all the other indices get reassigned. i.e. for example

consider: 

list = [i for i in range(1,11)]

to remove the elements at indices 1,3, and 5; we try the following:

for i in [1,3,5]:

    list.pop(i)

>>2

5

8

i.e. this method pops 2,5, and 8 the elements at 1,4, and 7th index. This happens exactly because of reassigning indices.

del method works again by index. del list[i] deletes the i th index of the list. For example, 

consider the same list =  [i for i in range(1,11)] as before. 

Now in writing del list[2], these will delete 3; which is at 2nd index.

The difference between pop and del is therefore only at one point, pop returns the element it removes, while del doesn't. That's why, del is more risky to use; as you will not get the return; and pop you can't use in an environment where you want specific outputs at the end of program, not random outputs like popped elements.

list.remove() works slightly differently in the sense that remove takes the element to delete as the parameter. It deletes the element in first occurrence if there are multiple presence of the same element. If you do want to remove an element completely, you will need to use while loop with count of the element and then use remove.

list[-1] = 'Conclusion'

So this was a basic introduction of list. Obviously there are many more things which you can actually do with lists; and you will. Comment below to let me know what are your suggestions or criticism as well as share with someone who can get helped from this introduction. 

Thanks for reading!


Comments

Popular posts from this blog

Mastering SQL for Data Science: Top SQL Interview Questions by Experience Level

Introduction: SQL (Structured Query Language) is a cornerstone of data manipulation and querying in data science. SQL technical rounds are designed to assess a candidate’s ability to work with databases, retrieve, and manipulate data efficiently. This guide provides a comprehensive list of SQL interview questions segmented by experience level—beginner, intermediate, and experienced. For each level, you'll find key questions designed to evaluate the candidate’s proficiency in SQL and their ability to solve data-related problems. The difficulty increases as the experience level rises, and the final section will guide you on how to prepare effectively for these rounds. Beginner (0-2 Years of Experience) At this stage, candidates are expected to know the basics of SQL, common commands, and elementary data manipulation. What is SQL? Explain its importance in data science. Hint: Think about querying, relational databases, and data manipulation. What is the difference between WHERE ...

What is Bort?

 Introduction: Bort, is the new and more optimized version of BERT; which came out this october from amazon science. I came to know about it today while parsing amazon science's news on facebook about bort. So Bort is the newest addition to the long list of great LM models with extra-ordinary achievements.  Why is Bort important? Bort, is a model of 5.5% effective and 16% total size of the original BERT model; and is 20x faster than BERT, while being able to surpass the BERT model in 20 out of 23 tasks; to quote the abstract of the paper,  ' it obtains performance improvements of between 0 . 3% and 31%, absolute, with respect to BERT-large, on multiple public natural language understanding (NLU) benchmarks. ' So what made this achievement possible? The main idea behind creation of Bort is to go beyond the shallow depth of weight pruning, connection deletion or merely factoring the NN into different matrix factorizations and thus distilling it. While methods like know...

Spacy errors and their solutions

 Introduction: There are a bunch of errors in spacy, which never makes sense until you get to the depth of it. In this post, we will analyze the attribute error E046 and why it occurs. (1) AttributeError: [E046] Can't retrieve unregistered extension attribute 'tag_name'. Did you forget to call the set_extension method? Let's first understand what the error means on superficial level. There is a tag_name extension in your code. i.e. from a doc object, probably you are calling doc._.tag_name. But spacy suggests to you that probably you forgot to call the set_extension method. So what to do from here? The problem in hand is that your extension is not created where it should have been created. Now in general this means that your pipeline is incorrect at some level.  So how should you solve it? Look into the pipeline of your spacy language object. Chances are that the pipeline component which creates the extension is not included in the pipeline. To check the pipe eleme...