Skip to main content

Command Palette

Search for a command to run...

List It Like a Pro: Your Ultimate Guide to Python Lists

Published
7 min read

Are you new to Python or Brushing up Python list?

If you are new then this blog will make you pro in mastering list or If you are brushing up,Still read it you can get to learn some interesting feature about list.

List are the most used data structure in Python.Above all, lists are the most flexible data structure, making Python stand out from other programming languages.

Accessing List Element

In Python, slicing works with the syntax [start:stop:step], where:

  • start is the index where the slice begins (inclusive).

  • stop is the index where the slice ends (exclusive).

  • step: (Optional) The step size or interval between each index in the slice.

list1 = [] ## empty list
list2 = [1, 2, 3] ## list of integers
list3 = [1, "One", 2.3] ## list with mixed data types

In list there is flexibility to keep various data types as collection.So if you want to access 2 from list2 you can get it by list2[1] .

list2 = [1, 2, 3] ## list of integers
list2[1]#2

In below example it starts from backward and will print skipping one value.

print(letters[-1:-3:-1])#['e', 'd']

For nested lists if you want to access 6 you can do it by list4[2][2].

list4 = ["One", [1, 2, 3], [4, 5, 6]]
list4[2][2]#6

Below is the example of nested list , which starts counting from the end of the list:-1 refers to the last element.

letters = ['a', 'b', 'c', 'd', 'e']
print(letters[-3:-1])

Memory Management of List in Python

Now, the question is how lists efficiently manage memory so that you don't have to declare the size of the list, unlike in other programming languages.

Python list are like array just like C.But difference is that it manages size of the list dynamically and it’s have a flexibility to store various type of data.

So when we are adding new elements in list it make the list size increase before that so that new element can be added there.Do you know python list doesn’t store actual value,it store reference to that object and with that reference we can get access of actual value.

If you delete any element in list do you know what happen?

If you delete any list item using pop,del ,remove(will discuss in later part of blog) it frees its memory and object are not referenced.Python always checks if there is any room in allocated buffer or not.IIf there is room in the allocated buffer, Python will add the new item. If not, Python creates a larger memory block, copies the items, and moves them to the new location.

Garbage Collector helps to handle Deleted items.And now question is What is Garbage Collector?

What is Garbage Collector?

In Python,it is a process of automatic cleaning of unused or unreachable objects where as for other programming language like C/C++ you have to manually delete them.Python have internal reference counter that tracks elements.Here when we do del operation on any list item then it decrement the reference count and when reference count become zero then object are unreachable.And then garbage collector comes as a Hero and remove and frees the memory.Python’s garbage collector works silently behind the scenes, making your coding life easier by managing memory efficiently.

Why I am telling this you must think.It helps to manage memory using list and avoid memory leaks and you can write clean and efficient code using list.

Why the lists are mutable in nature?

In list element can be changed after it is created that is why list are mutable . In below example third element of the list I modified and I am getting new list.

my_list = [10, 25, 5, 60, 15, True, False]
my_list[3] = 65
print(my_list)#[10, 25, 5, 65, 15, True, False]

Now I will talk some methods of list so that you can use it and save your time.Taking a list as example and showing it’s operations.

my_list = [10, 25, 5, 60, 15, True, False]

type()

With respect to Python list are defined as object with returning data type “list”.

type(my_list)

max()

It will print max value in a list.

max_element = max(my_list)#60

min()

It will print min value in a list.

min_element = min(my_list)#False

You are thinking why False because False will return 0 and true will return 1 so as 0 in minimal that’s why printing False.

sum_element = sum(my_list)strings = ["abc", "abd", "abe"]
min_string = min(strings)
max_string = max(strings)
print(min_string)#abc
print(max_string)#abe

Guess in string how max and min value handles.It handles on comparing each element of a list with respect to ASCII value.

Multiplication of List

print(my_list * 3) #[10, 25, 5, 65, 15, True, False, 10, 25, 5, 65, 15, True, False, 10, 25, 5, 65, 15, True, False]

append()

It will append new value to a list from end.In append more than one value cannot be appended will give that an error.

my_list.append(20)
print(my_list) #[10, 25, 5, 65, 15, True, False, 20]

extend()

l1.extend(l2) -> This modifies l1 in place.

It does not return anything -- its return value is None

l1 = [1, 2, 3, 4]
l2 = [5, 6, 7, 8]
l1.extend(l2)
print(l1)#[1, 2, 3, 4, 5, 6, 7, 8]

Below way of printing is wrong because the extend function does not return anything


l1= [1, 2, 3]
l2 = [4, 5, 6]
print(l1.extend(l2))#None

insert(index, data)

Insert will insert an element at that particular index.

my_list.insert(0, 5)
print(my_list)

'+' Operator

list1 = ['apple', 'banana']
list2 = ['cherry', 'date']
new_list = list1 + list2
print(new_list)#['apple', 'banana', 'cherry', 'date']

It will append list element in same list.

So you can have question extend is doing this same operation.Then what is the difference between extend() and +?
For extend it will get appended but for + list and tupple combination will give error.

a = [1, 2]
a.extend((3, 4))
print(a)#[1, 2, 3, 4]

a + (3, 4)
#---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-28-5d782613d2bf> in <cell line: 0>()
----> 1 a + (3, 4)

TypeError: can only concatenate list (not "tuple") to list

Comparison Of Lists

This will compare two list.

list1 = [1, 2, 3]
list2 = [4, 5, 6]

print(list1 == list2)#False
print(list1 != list2)#True
print(list1 < list2)#True 
print(list1 > list2)#False

remove()

It will remove first element from list.and return updated list.

my_list.remove(20)
my_list#[5, 10, 25, 5, 65, 15, True, False, 20]

pop()

It will remove element from given index if given else will remove from last and that will return removed value.

popped_element = my_list.pop(2)
print(popped_element)#25
print(my_list)#[5, 10, 5, 65, 15, True, False, 20]
my_list.pop()
print(my_list)#[5, 10, 5, 65, 15, True, False]

del Statement

It will delete list or it’s element from memory.

del my_list[1]
print(my_list)#[5, 5, 65, 15, True]
del my_list
print(my_list)
#my_list output:
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-45-7a103dd61563> in <cell line: 0>()
      1 del my_list
----> 2 print(my_list)

NameError: name 'my_list' is not defined

clear()

It will clear all element from list.

list4.clear()
print(list4)#[]

sort()

It will sort list in ascending or descending.

my_list = [3, 1, 4, 7, 8, 12, 0, 13, 16, 11]
my_list.sort()
print(my_list)#[0, 1, 3, 4, 7, 8, 11, 12, 13, 16]
my_list.sort(reverse=True)
print(my_list)#[16, 13, 12, 11, 8, 7, 4, 3, 1, 0]

count()

How many items present in list give that count.

count_element = my_list.count(16)
print(count_element)#1

index()

It will return position of first occurance of element.

index = my_list.index(4)
print(index)#6

reverse()

It will reverse the list element.

my_list.reverse()
print(my_list)#[0, 1, 3, 4, 7, 8, 11, 12, 13, 16]

join()

It will join list element and return a string.If any value is in join that use as a seperator.

words = ["Hello", "How", "are", "you"]
result = " ".join(words)
print(result)#Hello How are you

This much data is enough to handle list like a pro.Lists are versatile, easy to use, and powerful—once you master them, you unlock a wide range of Python programming capabilities. From handling user inputs, managing collections of data, to building algorithms and apps, lists are your go-to companion.