[Part VI]Lists in Python🐍

[Part VI]Lists in Python🐍

Learn about a useful data structure in Python called Lists.

Β·

5 min read

Welcome back to the series "Learn Python with me!"πŸ‘‹πŸ‘‹

We know how to deal with loops, functions, and even DocTests in Python. It is time to enter the world of data structures.

Every programmer searches for the term 'DSA' after knowing that it is crucial for technical interviews. Right after the Google SearchπŸ”, most of us close the tab feeling scared of it.

Today, I want you to shut those scary feelings and down and learn along with me.πŸ“ˆ

Let's get started with Lists in Python.

When we think of a list, we might think about our grocery list.

Grocery_list.png

This list is an ordered collection of items. After procuring the items, we can also scratch them off our list. If we recall another item later, we can add it to our list.

A list in Python🐍 works similarly.

What is a List in Python?

A list is a way to keep track of an ordered collection of items. We can also refer to the items in our list as elements.

A list is said to be:

Ordered: because we can refer to the elements by their position.

Collection: A list can contain multiple items.

A list can dynamically adjust its size, as and when elements are added or removed.

How can we create a list?

A list in Python starts and ends with square brackets[]. The elements are separated by commas.

grocery_list = ['Cereal','Flour','Coffee','Sugar','Dry Pasta']
family_age = [78,55,45,19,10]
mix = ['Luke', 007, False, 3.14]
empty_list = []

As you can see a list in Python can have all data types together.

Earlier, in the definition, you saw that a list is ordered.

Let's see how the ordering is done.

Take another list,say:

list = [2,4.6,3.14,"Luke","Leia",True]

Lists-Index (1).png

The ordering is done starting from 0.

Accessing an element

Let's consider the list above.

list = [2,4.6,3.14,"Luke","Leia",True]

We can access a list in Python by giving the element within square brackets.

Let's go back to our terminal to test it.

list_access.gif

Here, we can see that we got an index out of range error when we tried to access an element beyond its length.

The length of the list is 6, as there are 6 elements in it.

Note: The length of the list is 6, but the last element can be accessed by list[5]

Lists in Python have some very useful operations.

Length of a List

The length of a list can be found by using the function len()

len(list) -> gives the length of the list

Check if an element is present in the list

x in list -> checks whether the element x is present in the list or not and gives a boolean value.

Adding elements to a list

You can add elements to a list by using the function append().

list.append(x) -> will add x to the end of the list. This will increase the length of the list by 1. The list is changed in place.

You can also use the extend() function to add all elements of another list to the end of the list you want to change.

list.extend(list2) -> will add all elements of list2 at the end of list1. list2 remains unchanged.

Let's try these operations in the terminal.

list_operations.gif

Note: The + operator works similarly to the extend() function.

What is the difference between the append() and extend() functions?

Let's take two lists:

list1 = [1,2,3]

list2 = [4,5]

Now, we will try the append() and extend() functions on these.

  • list1.append(list2)

  • list1.extend(list2)

We will again go straight to our terminal 😁.

list_append_extend.gif

The append() function adds the whole list like an element. Whereas, the extend() function adds all the elements in the second list at the end of the first list.

Finding the index of an element in a list

You can find the index of an element in a list by using the index() function.

list.index(x) -> Looks for the first instance of x in the list and returns its index. It gives an error if x is not present in the list.

Find the minimum and maximum element in the list

min(list) -> Gives the minimum valued element present in the list.

max(list) -> Gives the maximum valued element present in the list.

Inserting elements in a list

list.insert(index,x) -> Will insert the element in the given index position, shifting elements towards the end of the list as needed.

Let's try these in the terminal.πŸ‘‡

list_index_max_min_insert.gif

We can loop over elements in a list using the for loop and the for-each loop.

For loop

list = [1,2,3,4,5]
for i in list:
    print(i)

OR

list = [1,2,3,4,5]
for i in range(len(list)):
    print(list[i])

For-each loop

Loops over all elements in a list once.

def main():
    avengers = ['Captain America','Iron Man','Black Widow','Hulk','Thor','Hawkeye']
    for avenger in avengers:
        print(avenger)



if __name__ == '__main__':
    main()

How should I take inputs from the user and store them in a list?

def main():
    list = []
    for i in range(10):
        list.append(i) #storing numbers 0-9 in the list
    print(list)

if __name__ == '__main__':
    main()

Congratulations!πŸŽ‰πŸŽ‰ You managed to learn about lists today!

More such operations can be found in the Python docs

All we have to do next time is start applying lists in our programming and learn more about the data structures in Python. Feel free to ask any doubts that you may have in the comments section below.

Β