Slice It, Dice It, Master It – The Art of Python Lists

Anindita GhoshAnindita Ghosh
6 min read

What is Data Structure?

At its most basic level, a data structure is a way of organizing data in computer memory, implemented in a programming language. This organization is required for efficient storage, retrieval, and modification of data. It is a fundamental concept as data structures are one of the main building blocks of any modern software. Learning what data structures exist and how to use them efficiently in different situations is one of the first steps toward learning any programming language.

Built-in data structures in Python can be divided into two broad categories: mutable and immutable. Mutable (from Latin mutabilis, "changeable") data structures are those that we can modify -- for example, by adding, removing, or changing their elements. Python has three mutable data structures: lists, dictionaries, and sets. Immutable data structures, on the other hand, are those that we cannot modify after their creation. The only basic built-in immutable data structure in Python is a tuple. In this blog we will discuss about “List” data structure.

Python List:

After starting with Python, we’ll soon bump into a super useful concept called a “list”. At first, the word “list” might sound a bit basic—we think of a shopping list or a to-do list. And actually… that’s not far off!

A Python list is just like that—a collection of items, grouped together in one place. It could be a list of numbers, names, tasks, or even a mix of different things. We can store them, access them, change them, or even remove them. Python lists are ordered (items stay in the same order unless you move them), and they’re mutable (which means you can change them any time you like—add, remove, or update things).

Think of a list like a backpack 🧳😉:
We can pack multiple items inside (books, pens, snacks), take them out when needed, swap one for another, or even rearrange them. That’s how flexible Python lists are!
Now the questions come into our mind:
"Can I store all my exam scores in one place?" Yes.
"Can I make a list of favorite songs and add new ones later?" Absolutely.
"Can I mix numbers, text, even other lists inside a list?" Yep, Python lets you do that too!

In this blog, we’ll dive into the world of Python lists and cover everything we need to know.

List Basics:

  • Lists maintain the order in which elements are added. This means you can access elements by their position within the list.

  • Lists can hold a mix of different data types. For example, you can have a list that contains strings, integers, Booleans, and even other lists.

  • Lists are mutable, which means you can change their elements, size, and structure during program execution.

Creating a List

To create a list in Python, you enclose a comma-separated sequence of elements in square brackets. Here’s an example of a list:

my_list = ["foo", "1", "hello", [], None, 2.3]

We can see that this list, my_list, contains a mix of data types, including strings, an empty list, None, and a floating-point number.

To check the data type of a variable, you can use the type function. For example:

my_list = ["foo", "1", "hello", [], None, 2.3]
print(type(my_list))     # Output: <class 'list'>

Length of a List

To find the length of a list in Python, you can use the len function. This function returns the number of elements in the list. Here's an example:

my_list = [10, 20, 30, 40, 50]
list_length = len(my_list)
print("The length of my_list is:", list_length)
# Output: 5

List Membership

We can check if a specific element is a member of a list using the in operator. It returns True If the element is found in the list and False If it is not. Here's an example:

fruits = ["apple", "banana", "cherry", "date"]
check_fruit = "banana"

if check_fruit in fruits:
    print(check_fruit, "is in the list.")
else:
    print(check_fruit, "is not in the list.")

# Output -> banana is in the list.

List Methods:

Let’s check all the methods we can use in the List:

MethodDescription
append()Adds an element at the end of the list
clear()Removes all the elements from the list
copy()Returns a copy of the list
count()Returns the number of elements with the specified value
extend()Add the elements of a list (or any iterable), to the end of the current list
index()Returns the index of the first element with the specified value
insert()Adds an element at the specified position
pop()Removes the element at the specified position
remove()Removes the first item with the specified value
reverse()Reverses the order of the list
sort()Sorts the list

Here is a pictorial example of methods in the List:

Python: List Methods and Operations - Python Coding

List Functions:

FunctionWhat It DoesExample
len()Returns the number of items in a listlen(my_list)
max()Returns the largest itemmax(my_list)
min()Returns the smallest itemmin(my_list)
sum()Adds all the numbers in the listsum(my_list)
sorted()Returns a new sorted version of the listsorted(my_list)
list()Converts something into a listlist("hello")['h','e',...]

List Slicing:

“List Slicing” is the process of extracting a part of a list using its indexing.

my_list = [1,"Four",9.6,2]
my_list[0:2]      # Output: [1, "Four"]
my_list[-2:]      # Output: [9.6, 2]
my_list[::-1]     # Output: [2, 9.6, "Four", 1]
my_list[-1]       # Output: 2

Python List Comprehension

List comprehensions generate new lists from other lists, strings, arrays, lists, etc. A typical list comprehension iterates over each element in a given expression and stores these values in a new list if the conditional statement is satisfied.

Let’s understand this by writing some code to find “even numbers” amongst the “first 10 natural numbers.” One of the conventional approaches involves using a ”for loop” as shown below:

even_numbers = []
for i in range(1, 11):
    if i % 2 == 0:
        even_numbers.append(i)

print(even_numbers)         # Output -> [2, 4, 6, 8, 10]

We can also access elements by using a for loop in a list-

Python List Tutorial: Lists, Loops, and More! – Dataquest

A list of lists (nested list):

A list of lists, also called a nested list, is simply a list where each element is itself a list.

nested_list = [[1, 2], [3, 4], [5, 6]]
print(nested_list[0])      # Output: [1, 2] (first sublist)
print(nested_list[-1])   # Output: [5, 6]   (last sublist)
print(nested_list[0][1])   # Output: 2      (second item in first sublist)

List Concatenation:

We simply use the addition operator (”+”) between two or more lists for list concatenation.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list)

Here are some code snippets in Colab about Python List:

Check List GIFs | Tenor

Conclusion:

This article has walked us through the various methods and operations of Python lists.

  1. We first discussed what “Python Lists” essentially are.

  2. Then we discussed various list operations like Creating a List, Accessing List Items, List Slicing, Extended Slicing, and List Concatenation.

  3. Discussed some essential Built-in functions in Lists

  4. We then looked at what List Comprehensions are.

  5. And finally ended the blog with commonly used List methods.

Hope you enjoyed reading this blog and gained some useful insights from it!

Thanks for reading!😁

26
Subscribe to my newsletter

Read articles from Anindita Ghosh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Anindita Ghosh
Anindita Ghosh