Advanced Python - I

Introduction to Lists

Simply put, a list is an ordered collection of items enclosed in [] and separated by commas. Lists in Python work like dynamic arrays, similar to vector in C++ or ArrayList in Java. 

Lists belong to Python’s sequence data types, just like tuples and strings.

Example of a List in Python

Let’s create a Python list:

cities = ["Paris", "Tokyo", "New York"] print(cities)

Output:

['Paris', 'Tokyo', 'New York']

Lists are the simplest containers and are fundamental in Python programming. They do not need to be homogeneous, which makes them versatile. A list can store integers, strings, objects, or mixed data types. Lists are mutable, meaning they can be modified after creation.

Creating a List in Python

Lists can be created by placing a series of items inside square brackets []. Unlike Sets, lists do not need a constructor function for creation.

👀Note: Unlike Sets, lists can hold mutable elements like other lists.

Examples:

Creating a Blank List

items = [] print("Blank List:") print(items)

Creating a List of Numbers

numbers = [5, 15, 25] print("\nList of Numbers:") print(numbers)

Creating a List of Strings and Accessing Elements

fruits = ["Apple", "Banana", "Cherry"] print("\nList Items:") print(fruits[0]) print(fruits[2])

Output:

Blank List: [] List of Numbers: [5, 15, 25] List Items: Apple Cherry

Accessing Elements from the List

List items are accessed by their index using square brackets []. Nested lists can be accessed with multiple indices.

Example 1: Accessing Elements from a List

colors = ["Red", "Green", "Blue"] print("Accessing an element from the list:") print(colors[0]) print(colors[2])

Output:

Accessing an element from the list: Red Blue

Example 2: Accessing Elements from a Multi-Dimensional List

matrix = [["a", "b"], ["c", "d"]] print("Accessing an element from a Multi-Dimensional list:") print(matrix[0][1]) print(matrix[1][0])

Output:

Accessing an element from a Multi-Dimensional list: b c

Negative Indexing

Negative indices access elements from the end of the list. For example, list[-1] retrieves the last item, list[-2] the second-last, etc.

data = [100, 200, "Hello", 400, "World"] print("Accessing element using negative indexing:") print(data[-1]) print(data[-3])

Output:

Accessing element using negative indexing: World Hello

Getting the Size of a List

Use the len() function to get the number of items in a list.

empty_list = [] print(len(empty_list)) values = [3, 7, 21] print(len(values))

Output:

0 3

Adding Elements to a Python List

append() Method

Use append() to add a single element to the end of a list. To add multiple items, loop through your data.

animals = [] print("Initial blank List:") print(animals) animals.append("Cat") animals.append("Dog") animals.append("Rabbit") print("\nList after adding three elements:") print(animals) for x in ["Lion", "Tiger", "Bear"]: animals.append(x) print("\nList after adding multiple animals:") print(animals) animals.append(("Deer", "Elk")) print("\nList after adding a tuple:") print(animals) other_list = ["Eagle", "Hawk"] animals.append(other_list) print("\nList after adding another list:") print(animals)

Output:

Initial blank List: [] List after adding three elements: ['Cat', 'Dog', 'Rabbit'] List after adding multiple animals: ['Cat', 'Dog', 'Rabbit', 'Lion', 'Tiger', 'Bear'] List after adding a tuple: ['Cat', 'Dog', 'Rabbit', 'Lion', 'Tiger', 'Bear', ('Deer', 'Elk')] List after adding another list: ['Cat', 'Dog', 'Rabbit', 'Lion', 'Tiger', 'Bear', ('Deer', 'Elk'), ['Eagle', 'Hawk']]

insert() Method

The insert() method adds an element at a specified index.

Syntax:

list_name.insert(index, element)
  • index: The position where to insert.

  • element: The element to insert.

Example 1: Inserting a String

languages = ["Python", "Java"] languages.insert(1, "C++") print(languages)

Output:

['Python', 'C++', 'Java']

Example 2: Inserting an Integer into a List

nums = [10, 20, 30, 40, 50] nums.insert(3, 999) print(nums)

Output:

[10, 20, 30, 999, 40, 50]

count() Method

The count() method counts how many times a value appears in a list.

Syntax:

list_name.count(object)

Example:

letters = ['x', 'x', 'y', 'z', 'x', 'z'] print(letters.count('z'))

Output:

2

del Keyword

The del keyword removes items by index or deletes the entire list.

Syntax:

del list_name[index] # delete single element del list_name # delete entire list

Example:

scores = [5, 10, 15, 10, 20] del scores[1] print(scores) del scores[-1] print(scores) del scores[0] print(scores)

Output:

[5, 15, 10, 20] [5, 15, 10] [15, 10]

remove() Method

The remove() method deletes the first occurrence of a specified value.

Syntax:

list_name.remove(value)

Example:

numbers = [9, 8, 7, 8, 6, 5] numbers.remove(8) print(numbers) numbers.remove(5) print(numbers)

Output:

[9, 7, 8, 6, 5] [9, 7, 8, 6]

pop() Method

The pop() method removes and returns an item at a specific index. If no index is given, it pops the last item.

Syntax:

list_name.pop(index)

Example:

items = [100, 200, 300, 400, 500] items.pop(2) print(items) items.pop(-1) print(items) items.pop(0) print(items)

Output:

[100, 200, 400, 500] [100, 200, 400] [200, 400]

max() Method

The max() function returns the largest element among the values given. For strings, it returns the lexicographically highest value.

Syntax:

max(a, b, c, ..., key=None, default=None)

Example:

print("Maximum of 7, 22, 15.5, 44, and 5 is:", end="") print(max(7, 22, 15.5, 44, 5))

Output:

Maximum of 7, 22, 15.5, 44, and 5 is:44

min() Method

The min() function returns the smallest element among the arguments. For strings, it returns the lexicographically smallest string.

Syntax:

min(a, b, c, ..., key=None, default=None)

Example:

print("Minimum of 7, 22, 15.5, 44, and 5 is:", end="") print(min(7, 22, 15.5, 44, 5))

Output:

Minimum of 7, 22, 15.5, 44, and 5 is:5

sort() Method

The sort() method arranges list elements in ascending or descending order.

Syntax:

list_name.sort(reverse=True/False, key=None)
  • reverse: True for descending order.

  • key: A function to decide sorting logic.

Example 1: Sort Numbers in Ascending Order

values = [9, 3, 12, 7] values.sort() print(values)

Output:

[3, 7, 9, 12]

reverse() Method

The reverse() method reverses the list in place.

Syntax:

list_name.reverse()

Example:

numbers = [10, 20, 30, 40] numbers.reverse() print(numbers) letters = ['m', 'n', 'o', 'p'] letters.reverse() print(letters)

Output:

[40, 30, 20, 10] ['p', 'o', 'n', 'm']

Popular Posts