Day 12: Lists in Python

Similar to arrays in javascript, Lists are ordered collection of values in Python.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print (numbers) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print (numbers[3]) # 4
print (numbers[-1]) # 10
print (numbers[3:6]) # [4, 5, 6]

numbers[3] = -12.4 
print (numbers) # [1, 2, 3, -12.4, 5, 6, 7, 8, 9, 10]
print (len(numbers)) # 10

# numbers[11] = 11 # out of range error

Lists can have any type of data

rand_data = [1, "soumil", True, 3.14, []]
print (rand_data) # [1, 'soumil', True, 3.14, []]

List Methods

list.append(item) appends value at end of list.

numbers.append(342) # adds 342 to the end of the list
print (numbers) # [1, 2, 3, -12.4, 5, 6, 7, 8, 9, 10, 342]

list.extend(another_list) adds all the values of an iterable to the end of the list

negative_numbers = [-3, -2, -1]
numbers.extend(negative_numbers) 
print (numbers) # [1, 2, 3, -12.4, 5, 6, 7, 8, 9, 10, 342, -3, -2, -1]

list.insert(index, value) inserts value on list index

star_war_characters = ['Han Solo', 'C-3PO', 'R2-D2', 'Luke Skywalker', 'Leia Organa', 'Obi-Wan Kenobi']

star_war_characters.insert(3, 'Chewbacca'
print (star_war_characters) # ['Han Solo', 'C-3PO', 'R2-D2', 'Chewbacca', 'Luke Skywalker', 'Leia Organa', 'Obi-Wan Kenobi']

List slicing, replacing sliced lists, clearing lists, remove list item

print(star_war_characters[4:])  # ['Luke Skywalker', 'Leia Organa', 'Obi-Wan Kenobi']
print(star_war_characters[1:7:2])  # ['C-3PO', 'Chewbacca', 'Leia Organa']
print(star_war_characters[::2])  # ['Han Solo', 'R2-D2', 'Luke Skywalker', 'Obi-Wan Kenobi']

# replacing sliced lists
star_war_characters[1:3] = ["Vader", "Mando", "Moff Gideon"]  # ['Han Solo', 'Vader', 'Mando', 'Chewbacca', 'Luke Skywalker',
# 'Leia Organa', 'Obi-Wan Kenobi']

# Clear list - remove all values from lists
star_war_characters.clear()
print(star_war_characters) # []

# Remove first item from list
star_war_characters.remove("Moff Gideon")

list.count(arg) counts instances in a list

# Count number of times a value is present in list else return 0
# list.count takes 1 arg else throws error
list = [1, "Soumil", "soumil@gmail.com",
        ["Kolkata", "Shimla", "Delhi"], 1, 4, 5, 6, 5, 2, 5]
print(list.count(1))  # 2
print(list.count(5))  # 3
print(list.count(123))  # 0

Nested lists

numbers = [1, 2, 3, 4, [5, 6, 7, 8, [9, 10, 11, 12]]]
print(numbers) # [1, 2, 3, 4, [5, 6, 7, 8, [9, 10, 11, 12]]]
print (len(numbers)) # 5
print(numbers[3]) # 4
print(numbers[4]) # [5, 6, 7, 8, [9, 10, 11, 12]]
print(numbers[4][0]) # 5
print(numbers[4][2]) # 7
print(numbers[4][4]) # [9, 10, 11, 12]
print(numbers[4][4][3]) # 12

star_war_chars = [
    ['Darth', 'Vader'],
    ['Luke', 'Skywalker'],
    ['Han', 'Solo'],
]

print(star_war_chars[2][1])  # Han Solo
print(star_war_chars[0][1])  # Han

List operators

# concatenate lists [12, 13, 14, 15, 16, 17]
print([12, 13, 14] + [15, 16, 17])

# TypeError: can only concatenate list (not "int") to list
# print([12, 13, 14] + 5)

# Multiply lists
# [12, 13, 14, [21, 22, 23], 12, 13, 14, [21, 22, 23], 12, 13, 14, [21, 22, 23]]
print([12, 13, 14, [21, 22, 23]] * 3)
print([1, 2, 3, 1, 1] * 5)  # [1, 2, 3, 1, 1, 1, 1, 1, 1, 1]

“in” operator

# Check if value is present in list
list = [1, "Soumil", "soumil@gmail.com", ["Kolkata", "Shimla", "Delhi"]]

print(1 in list)  # True
print("Soumil" in list)  # True
print("soumil@yahoo.com" in list)  # False
print("Kolkata" in list)  # False
print("Delhi" in list[3])  # True

“==” operator

The == operator in lists compares values of 2 lists to find its equal or not.

print([1, 2] == [1, 2])  # True
print([1, 2] == [1, 2, 3])  # False
print([1, 2] == [2, 1])  # False

“is” operator

The is operator is used to compare the identity of the operator a.k.a same location in memory

num1 = [1, 2, 3]
num2 = [1, 2, 3]
num3 = num2

print(num1 == num2)  # True
print(num1 is num2)  # False
print(num2 is num3)  # True

Lists unpacking

# list destructuring (unpacking)
user = ["Soumil", "Roy", "Full Stack Developer"]
first_name, last_name, job = user
print(first_name, last_name, job)

# f_name, l_name = user # Error - too many values
# To fix this, we can use the * operator (similar to rest operator in JS)
f_name, *rest = user
print(f_name, rest)  # Soumil ['Roy', 'Full Stack Developer']

List duplication

The list.copy()method creates a shallow copy

# Duplicating a list
customer = ["John", "Doe", 42]
updated_customer = customer.copy()
print(updated_customer)  # ["John", "Doe", 42]
customer[0] = "Soumil"
updated_customer[1] = "Roy"
print(customer)  # ['Soumil', 'Doe', 42]
print(updated_customer)  # ['John', 'Roy', 42]
print(customer is updated_customer)  # False

# another way to copy list
another_copy = customer[:]
print(another_copy)  # ['Soumil', 'Doe', 42]
print(id(customer), id(another_copy))

Nested list copy problem

# Nested lists copy
nested_list = [1, 2, 3, 4, [5, 6, 7, 8, [9, 10, 11, 12]]]
# Shallow copy, only copies the first level of the list
copied_nested_list = nested_list.copy()
print(copied_nested_list)  # [1, 2, 3, 4, [5, 6, 7, 8, [9, 10, 11, 12]]]

# lets modify original lists nested list
nested_list[4][1] = -1
print(copied_nested_list)  # [1, 2, 3, 4, [5, -1, 7, 8, [9, 10, 11, 12]]]

# nested lists point to original list, thus modifying parent object nested item is reflected on copied list as well. To prevent, we should use deepcopy

Author: Soumil Roy

I'm a Frontend Engineer currently building expertise in React, TypeScript & GraphQL

Leave a Reply

Your email address will not be published.