Using List Data Structures In Python😋

Data structures are a special way for storing and accessing data. Every programming language has some built-in data structures such as arrays, lists, and so on ….

In this article, we will briefly discuss using List data structure by trying to create, manipulate and access element from the list.

A list in Python is denoted by a pair of matching square brackets [ ].

Creating an Empty List 

initial_list = []
print(initial_list)

Output   [ ]

Creating a Populated list 

Programming_languages = ['Java','Python', 'C', 'c++', 42]
print(Programming_languages)

It will print each element in the list in exactly the same sequence as you coded. The individual element in the list is separated by ','

Output ['Java','Python', 'C', 'c++', 42

Accessing Element

To access the element from the list we need to use the index number. The index must be an integer. Let's see a few examples:

print(Programming_languages[0])

The above snippet will return first element in the list:

print(Programming_languages[1:3])

The above snippet returns you all the elements between the 2nd and the 4th element (excluding the 4th element).

Negative Indexing

It also allows negative indexing. The index of -1 refers to the last item, -2 to the second last item, and so on. 

print(Programming_languages[-1])

The above snippet returns the last element from the list:

print(Programming_languages[2:])

The above snippet returns all the elements starting from 3rd element of the list all the way end of the list.

You must know,

List can be used as both,

  • Queue - FIFO (First In First Out): A queue is something where the first item that comes into the queue is also the first item get out of the Queue.
  • Stack - LIFO (Last In First Out): In stack the element pushed in last get popped out first.

Let's see some more examples in list:

Programming_languages.pop()

Here, pop will pull out the last element of the string. 

Note: we are adding element to the list to the right end every time.

Programming_languages.pop(0)

Here it will remove the first element from the string.

Note
In List, the pop operation will change the value of variable.

Adding Element to the List

Element in the list can be added by using built-in functions.

Append()

Only one element at a time can be added to the list by using append function. List can also be added to the existing list by using append function but append will only add the element at the end of the list.

Insert()

Insert function will insert an element at desired position and will take two arguments like (position, value).

The list has many more methods.


Similar Articles