List, tuple and dict

List

A list is a collection of items that are ordered and changeable. Lists are defined by enclosing the elements in square brackets [].

# List of integers
numbers = [1, 2, 3, 4, 5]
print(numbers)

# List of strings
fruits = ['apple', 'banana', 'cherry']
print(fruits)

# List of mixed data types
mixed = [1, 'apple', 2.5]
print(mixed)

Accessing elements

The elements of a list can be accessed using the index of the element. The index starts from 0.

numbers = [1, 2, 3, 4, 5]
print(numbers[0]) 
print(numbers[1])

# Negative indexing
print(numbers[-1]) # Last element
print(numbers[-2]) # Second last element

Slicing

Slice of a list is a part of the list. Slicing is done using the colon : operator.

numbers = [1, 2, 3, 4, 5]
print(numbers[1:3]) # [2, 3], index 1 to 2
print(numbers[:3])  # [1, 2, 3], index 0 to 2
print(numbers[2:])  # [3, 4, 5], index 2 to end

Modifying elements

Elements of a list can be modified by assigning new values to the index.

numbers = [1, 2, 3, 4, 5]
numbers[2] = 10
print(numbers) # [1, 2, 10, 4, 5]

List methods

Python provides several methods to work with lists. Some of the commonly used methods are:

  • append(): Adds an element at the end of the list.

  • insert(): Adds an element at the specified position.

  • remove(): Removes the first occurrence of the element with the specified value.

  • pop(): Removes the element at the specified position.

  • sort(): Sorts the list.

  • reverse(): Reverses the order of the list.

numbers = [1, 2, 3, 4, 5]
numbers.append(6)
print(numbers) # [1, 2, 3, 4, 5, 6]

numbers.insert(2, 10)
print(numbers) # [1, 2, 10, 3, 4, 5, 6]

numbers.remove(3)
print(numbers) # [1, 2, 10, 4, 5, 6]

numbers.pop(2)
print(numbers) # [1, 2, 4, 5, 6]

numbers.sort()
print(numbers) # [1, 2, 4, 5, 6]

numbers.reverse()
print(numbers) # [6, 5, 4, 2, 1]

Multi-dimensional lists

A list can contain other lists.

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[0]) # [1, 2, 3]
print(matrix[1][1]) # 5

Tuple

A tuple is a collection of items that are ordered and unchangeable. Tuples are defined by enclosing the elements in parentheses ().

The difference between a list and a tuple is that a tuple is immutable, i.e., the elements of a tuple cannot be changed.

# Tuple of integers
numbers = (1, 2, 3, 4, 5)
print(numbers)

Dictionary

A dictionary is a collection of items that are unordered, changeable, and indexed. Dictionaries are defined by enclosing the elements in curly braces {}. Each element in a dictionary is a key-value pair.

# Dictionary of key-value pairs
person = {
    'name': 'Alice',
    'age': 25,
    'city': 'New York'
}
print(person)

In this example, name, age, and city are the keys, and Alice, 25, and New York are the values.

Last updated