All About List Data Type in Python for Data Science

Rina Mondal
7 min readJan 8, 2024

--

List is a built-in data type that represents a collection of elements.

Lists are versatile and can contain elements of different data types, including numbers, strings, and other lists.

Lists are defined by enclosing elements in square brackets ([]) and separating them with commas.

In this blog, I will describe everything about list in Python:

List functions

Here’s a basic example of a list:

my_list = [1, 2, 3, 'four', 5.0]

Here, my_list contains integers, string, float together.

Creating a List:

# Empty
print([])// It will create a blank list

# 1D Homogeneous
print([1, 2, 3, 4])// It will create a homogeneous 1D integer list

# 2D Heterogeneous
print([1, 2, 3, [4, 5]])//It will create a homogeneous 2D list

# 3D
print([[[1, 2], [3, 4], [5, 6], [7, 8]]])// It will create a homogeneous 3D list

# Heterogeneous_list
print([1, 'two', 3.0, [4, 5], {'key': 'value'}])// A list can contain any other data types including dictionary.

print(list(range(5))) //To create a list using the list() function with the value 5, an iterable can be passed as an argument
O/t- 
[]
[1, 2, 3, 4]
[1, 2, 3, [4, 5]]
[[[1, 2], [3, 4], [5, 6], [7, 8]]]
[1, 'two', 3.0, [4, 5], {'key': 'value'}]
[0, 1, 2, 3, 4]

Accessing items from a list: By Indexing and Slicing, elements from the list can be accessed.

  1. Indexing: List is known as zero based indexing. This means that the first element is accessed with an index of 0, the second with an index of 1, and so on.
#Indexing
List=[1,2,3,4,5,6]
print(List[0])

#output
1

Python also supports negative indexing. In this case, -1 refers to the last element, -2 to the second-to-last, and so forth.

List=[1,2,3,4,5,6]
Print(List[-1])

#output
6

2. Slicing: Slicing in programming refers to extracting a portion or a subsequence from list. The basic syntax for slicing is start:stop:step. Here's how it works:

  • start: The index of the first element you want in the slice (inclusive).
  • stop: The index of the first element you don't want in the slice (exclusive).
  • step: The step size between elements.
# List Slicing
friend = ["harry","tom","rani","raja","ram","sam"]
print(friend[:3])// First three items of the list
print(friend[-3:])// All the items of the list except the except the first three items

#Output
['harry', 'tom', 'rani']
['raja', 'ram', 'sam']
#Slicing examples
l=[1, 7, 9, 11, 15, 0]
print(l[1:7])
print(l[1:7:1])
print(l[1:7:2])
print(l[-1:-5:-1]) #negative slicing. To do reverse printing
print(l[-1:-5:-2]) #Reverse printing with step size of 2
print(l[-5:-1:1]) #printing using neative indexing
print(l[-5:-1:2])

#Output
[7, 9, 11, 15, 0]
[7, 9, 11, 15, 0]
[7, 11, 0]
[0, 15, 11, 9]
[0, 11]
[7, 9, 11, 15]
[7, 11]
If start is omitted, it defaults to the beginning of the sequence.
If stop is omitted, it defaults to the end of the sequence.
If step is omitted, it defaults to 1.

l=[1, 7, 9, 11, 15, 10]
print(l[:7]) # start is omitted
print(l[1::1]) #end is omitted
print(l[1:7]) #step is omitted

#O/t- [1, 7, 9, 11, 15, 10]
[7, 9, 11, 15, 10]
[7, 9, 11, 15, 10]

3. Loop: you can use loops to iterate over the elements of a list.

# Iterating over each element in the list using a for loopL= [11,2,3,4,5]
for element in L:
print(element)
# Output:
1
2
3
4
5

Adding items to the List:

In Python, both the append() and extend() methods are used with lists to add elements, but they have different behaviors:

  1. append() Method:
  • The append() method is used to add a single element to the end of a list.
  • It takes one argument, which is the element you want to add.
  • It modifies the original list in place.
my_list = [1, 2, 3] 
my_list.append(4) # Result: [1, 2, 3, 4]

my_list=[1,2,3]
my_list.append([4,5]) # Result: [1, 2, 3, [4,5]]

2. extend() Method:

  • The extend() method is used to append the elements of an iterable (such as a list, tuple, or string) to the end of the list.
  • It takes one argument, which is the iterable containing elements to be added.
  • It modifies the original list in place
my_list = [1, 2, 3] my_list.extend([4, 5]) 
# Result: [1, 2, 3, 4, 5]

It’s important to note that extend() takes an iterable as an argument, whereas append() takes a single element.

3. The insert() method in Python is used to insert an element at a specified index in a list.

L=[1,2,3,4,5]
L.insert(1,9)
print(L)

#Output
[1,9,2,3,4,5]

Editing items in the list: Indexing or slicing can be used to edit the list.

L=[1,2,3,4,5]
# editing with indexing
L[-1]=50
# editing with slicing
L[1:4]=[20,30,40]
print(L)

#Output
[1,2,3,4,50]
[1,20,30,40,5]

Deleting items in the list:

  1. del (): statement removes the item based on index.
my_list = [1, 2, 3, 4, 5]

# Delete item at index 2
del my_list[2]
print(my_list)

#Output
my_list =[1,2,4,5]

2. remove() — removes the item based on the value.

my_list = [1, 2, 3, 4, 5]

# Remove item with value 3
my_list.remove(3)
print(my_list)

#Output
my_list=[1,2,4,5]

3. Pop(): used to remove and return an item from a specific index in a list. If you don’t provide an index to pop(), it will remove and return the last item by default.

4. Clear(): used to remove all elements from a list. It modifies the original list, making it empty.

my_list = [1, 2, 3, 4, 5]

# Clear all elements from the list
my_list.clear()

print("Updated list:", my_list)

Operations on List:

Arithmetic:

1. +operator: To concatenate two or more lists.

L1 = [1, 2, 3]
L2 = [4, 5, 6]

concatenated_list = L1 + L2
print(concatenated_list)

# Output: [1, 2, 3, 4, 5, 6]

2. * operator: To repeat a list.

L = [1, 2, 3]

repeated_list = L* 3
print(repeated_list)

# Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]

Membership: The membership operators (in and not in) are used to test whether a value or element is a member of a sequence

L = [1, 2, 3, 4, 5]

# Membership test
print(3 in L)
# Output: True

print(6 in L)
# Output: False

# Negation of membership test
print(3 not in L)
# Output: False

print(6 not in L)
# Output: True

List Function: Different functions can be performed on a list:

  1. Min/Max/ Sorted/len function can be applied on list function.
len/min/max/sorted
L = [3, 1, 4, 1, 5, 9, 2]
length = len(L)
minimum_value = min(L)
maximum_value = max(L)
sorted_list = sorted(L)
print("Minimum:", minimum_value)
print("Maximum:", maximum_value)

# Output:
# Length: 7
# Minimum: 1
# Maximum: 9
# Sorted List: [1, 1, 2, 3, 4, 5, 9]

2. Count(): used to count the number of occurrences of a specific element in a list

L = [1, 2, 3, 2, 4, 1, 5, 2]
count_of_2 = L.count(2)

print(count_of_2)

# Output: 3

3. index() used to find the index of the first occurrence of a specified value in a list.

L = [1, 2, 3, 2, 4, 1, 5, 2]
index_of_2 = L.index(2)

print(index_of_2)
# Output: 1

4. reverse() method is applied to the list, and it modifies the list in place, reversing the order of its elements.

L = [1, 2, 3, 4, 5]
L.reverse()

print(L)
# Output: [5, 4, 3, 2, 1]

5. sort() is a method that works on lists directly and sorts them in place, while sorted() is a function that takes an iterable, creates a new sorted list, and leaves the original iterable unchanged.

#sort vs sorted
L=[9,1,2,3,8,4,5]
print(L)
print(sorted(L))
print(L)
L.sort()
print(L)

#Output
[9,1,2,3,8,4,5]
[1,2,3,4,5,8,9]
[9,1,2,3,8,4,5]
[1,2,3,4,5,8,9]

6. copy() function is used for creating a shallow copy of a list, meaning it copies the references to the objects in the original list.

List Comprehension:

Advantages: Making code more concise, readable, and sometimes even more efficient.

The basic syntax of a list comprehension:

new_list = [expression for item in iterable if condition]

Here’s a breakdown of the components:

  • expression: The expression to be evaluated and included in the new list.
  • item: The variable representing each element in the iterable.
  • iterable: The existing iterable (e.g., list, tuple, string) that is being processed.
  • condition: A condition that filters which items from the iterable are included in the new list.
#Scalar multiplication on a vector
v=[2,3,4]
s=-3
[s*i for i in v]

#Output
[-6,-9,-12]

In summary, list has many importance:

  1. Ordered Sequences: Lists maintain the order of elements, meaning the order in which elements are added is preserved.

2. Mutable: Lists in Python are mutable, which means you can modify their contents by adding, removing, or modifying elements.

3. Indexing and Slicing: Lists support indexing, allowing you to access individual elements by their position. Slicing allows you to extract, making it easy to work with portions of the data.

4. Heterogeneous: Lists can contain elements of different data types. This versatility is useful when dealing with complex data structures.

5. Dynamic Memory Allocation: Lists automatically manage memory. As you add or remove elements, the list dynamically adjusts its size, making it efficient for various data storage needs.

While working with lists in programming provides numerous advantages, there are a few small drawbacks to keep in mind:

Python lists have dynamic typing overhead, memory overhead, and exhibit linear time complexity for operations like insertions and deletions due to their resizing mechanism. The mutability of lists, while often advantageous, can lead to unintended side effects if not handled carefully. Modifying a list in one part of the code may affect other parts, potentially causing unexpected behavior.

Conclusion: Despite these small disadvantages, lists remain a versatile and widely used data structure, especially for scenarios where the benefits, such as constant-time indexing and dynamic resizing outweigh the drawbacks. Understanding these nuances allows programmers to make informed decisions based on the specific requirements of their applications.

Give it :👏👏👏👏:
If you found this guide helpful , why not show some love? Give it a Clap 👏, and if you have questions or topics you’d like to explore further, drop a comment 💬 below 👇.. If you appreciate my hard work. Please follow me. That is the only way I can continue my Passion.

--

--

Rina Mondal

I have an 8 years of experience and I always enjoyed writing articles. If you appreciate my hard work, please follow me, then only I can continue my passion.