Built-in data Structures

 

Built-in Data Structures

List

list in Python is a mutable, ordered collection used to store multiple items in a single variable. It is one of the most commonly used data structures in Python.

Key Characteristics of Lists

  1. Ordered

    • Items are stored in the order they are added.
    • The order is preserved unless explicitly modified.
  2. Mutable

    • Lists can be changed after creation.
    • You can:
      • Add (append()insert()extend())

      • Remove (remove()pop()del)

      • Modify items (list[index] = new_value)

  3. Heterogeneous

    • A list can store elements of different data types:

      my_list = [42, "hello", 3.14, [1, 2]]
  4. Indexed

    • Elements are accessed by position (index), starting at 0:

      print(my_list[0]) # Output: 42
  5. Dynamic Size

    • Lists can grow or shrink in size dynamically as elements are added or removed.


List Accessing:

In Python, you access list elements using indexing or slicing.

1. Indexing

  • We can use the index operator [] to access an item in a list. List indices start at 0.

  • You can use positive or negative indices.

     my_list = ['apple', 'banana', 'cherry', 'date']
    
ElementIndex Negative Index
'apple'0         -4
'banana'   1-3
'cherry'2-2
'date'3-1

print(my_list[1])    # Output: banana
print(my_list[-1])   # Output: date

2. Slicing

It is used to access a range of elements. The values stored in a list can be accessed using the slice operator [] and [:] with indexes starting at 0 in the beginning of the list and working their way to end -1.

# Syntax: list[start:stop:step]
print(my_list[1:3]) # Output: ['banana', 'cherry']
print(my_list[:2]) # Output: ['apple', 'banana']
print(my_list[::2]) # Output: ['apple', 'cherry']

Looping through a list:

for fruit in my_list:
print(fruit)

Output:
apple
banana
cherry
date

List Operations:

1. Addition (+ Operator)

  • Combines two lists into a new list.

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

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

2. Multiplication (* Operator)

  • Repeats the elements in a list.

list1 = ['A', 'B']
result = list1 * 3
print(result)

Output: ['A', 'B', 'A', 'B', 'A', 'B']

3. Updation of List Elements

  • You can update a single element:

my_list = [10, 20, 30]
my_list[1] = 99
print(my_list)

Output: [10, 99, 30]
  • Or multiple elements using slicing:
my_list[0:2] = [1, 2]
print(my_list)

Output: [1, 2, 30]

4. Deletion of List Elements

Using del Statement:
my_list = [10, 20, 30, 40]
del my_list[1]
print(my_list)

Output: [10, 30, 40]

Using remove() Method:

  • Removes the first occurrence of a value.

my_list = [1, 2, 3, 2]
my_list.remove(2)
print(my_list)

Output: [1, 3, 2]


Built-in functions

Python provides a rich set of built-in functions to work with lists, one of the most commonly used data structures.
Below is a list of commonly used built-in functions and methods associated with Python lists:

1. len()

Returns the number of items in the list.

Example:

fruits = ['apple', 'banana', 'cherry']
print(len(fruits)) → Output: 3

2. max() and min()

Returns the maximum or minimum value from the list.

Example:

numbers = [10, 50, 20, 5]
print(max(numbers)) → Output: 50
print(min(numbers)) → Output: 5

3. sum()

Returns the sum of all numeric elements in the list.

Example:

numbers = [10, 20, 30]
print(sum(numbers)) → Output: 60

4. sorted()

Returns a new list that is a sorted version of the original.

Example:

nums = [3, 1, 4, 1, 5]
print(sorted(nums)) → Output: [1, 1, 3, 4, 5]

5. list()

Converts an iterable (like a string, tuple, or range) into a list.

Example:

text = "hello"
print(list(text)) → Output: ['h', 'e', 'l', 'l', 'o']

6. any() and all()

  • any() returns True if any element is True

  • all() returns True only if all elements are True.

Example:

values = [0, 1, 2]
print(any(values)) → Output: True
print(all(values)) → Output: False

7. enumerate()

Returns an enumerate object that includes index and value.

Example:

fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits): print(index, fruit)

Output:

0 apple
1 banana
2 cherry

8. zip()

Combines multiple iterables into tuples.

Example:

names = ['Alice', 'Bob']
scores = [85, 90]
result = list(zip(names, scores))
print(result) → Output: [('Alice', 85), ('Bob', 90)]

Tuple

A tuple is a built-in data structure in Python that works similarly to a list.
However, the key difference is that tuples are immutable,
meaning their values cannot be changed once assigned,
whereas lists are mutable and allow modifications.

Key Differences Between List and Tuple:
  • A list is enclosed in square brackets, like my_list = [1, 2, 3]
  • A tuple is enclosed in parentheses, like my_tuple = (1, 2, 3)
  • Lists allow changes to their elements, while tuples do not.
Benefits of Using Tuples:
  • Tuples can be used as keys in dictionaries because they are hashable. Lists cannot be used as dictionary keys.
  • Tuples are generally used for heterogeneous data (different types), while lists are preferred for homogeneous data (similar types).
  • Since tuples are immutable, iteration through a tuple is faster than a list, offering a slight performance improvement.

Creating a Tuple in Python

A tuple is created by placing all the elements inside parentheses (), with each element separated by a comma.

tup1 = (1, 2, 3, 4, 5)
tup2 = ('apple', 'mango', 'guava', 'orange')

You can also create an empty tuple that contains no elements. This is done by simply using empty parentheses:
tup = ().
To write a tuple containing a single value, there must be a comma at the end of the value, even though there is only one value. tup=(10,) A tuple can have any number of items, and they may be of different types (integer, float, list, string etc.) tup=(10,'Swathi',97.3,'B',)

Accessing The Tuple Elements:

There are various ways in which we can access the elements of a tuple.
1. Indexing
We can use the index operator [] to access an item in a tuple, where the index starts from 0. So, a tuple having 6 elements will have indices from 0 to 5. Trying to access an index outside of the tuple index range(6,7,... in this example) will raise an IndexError. The index must be an integer, so we cannot use float or other types. This will result in TypeError. Example: # Accessing tuple elements using indexing my_tuple = ('p','e','r','m','i','t') print(my_tuple[0]) # 'p'
print(my_tuple[5]) # 't'
Output: p t
2. Negative Indexing
Python allows negative indexing for its sequences.
The index of -1 refers to the last item, -2 to the second last item and so on. Example: # Negative indexing for accessing tuple elements my_tuple = ('p', 'e', 'r', 'm', 'i', 't') # Output: 't' print(my_tuple[-1]) # Output: 'p' print(my_tuple[-6])
Output: t p

3. Slicing
We can access a range of items in a tuple by using the slicing operator colon :. Example: # Accessing tuple elements using slicing my_tuple = ('p','r','o','g','r','a','m') # elements 2nd to 4th print(my_tuple[1:4]) # elements beginning to 2nd print(my_tuple[:-5]) # elements 3th to end
print(my_tuple[3:]) # elements beginning to end print(my_tuple[:])
Output:
('r', 'o', 'g')
('p', 'r')
('g', 'r', 'a', 'm')
('p', 'r', 'o', 'g', 'r', 'a', 'm')

Tuple Operations

Various Operations can be performed on Tuple. Operations performed on Tuple are given as: 
a) Adding Tuple: 
Tuple can be added by using the concatenation operator(+) to join two tuples. 
eg: 
 data1=(1,2,3,4)
 data2=('x','y','z')
 data3=data1+data2
 print (data1)
 print (data2) 
 print (data3)

Output:
(1, 2, 3, 4)
('x', 'y', 'z') 
(1, 2, 3, 4, 'x', 'y', 'z')

b) Replicating Tuple: 
Replicating means repeating. It can be performed by using '*' operator by a specific number of times. 
Eg: 
 tuple1=(10,20,30)
 tuple2=(40,50,60)
 print (tuple1*2) 
 print (tuple2*3) 
Output:
 (10, 20, 30, 10, 20, 30)
 (40, 50, 60, 40, 50, 60, 40, 50, 60)

c) Deleting elements from Tuple: 
Deleting individual element from a tuple is not supported. However the whole of the tuple can be deleted using the del statement. 
Eg:
 data=(10,20,'rahul',40.6,'z')
 print (data)
 del (data) #will delete the tuple data 
 print (data) #will show an error since tuple data is already deleted 
Output:
 (10, 20, 'rahul', 40.6, 'z')
 Traceback (most recent call last): File "C:/Python27/t.py", line 4, in print data NameError: name 'data' is not defined

Built-in tuple functions
 
FunctionDescriptionExample Usage
len(tuple)Returns the number of items in the tuple.len((1, 2, 3)) → 3
max(tuple)Returns the largest item. Works with numbers or strings.max((3, 5, 1)) → 5
min(tuple)Returns the smallest item.min((3, 5, 1)) → 1
tuple(sequence)Converts a list, string, or other iterable into a tuple.tuple([1, 2]) → (1, 2)
sum(tuple)Returns the total sum of elements (if all are numeric).sum((1, 2, 3)) → 6
sorted(tuple)Returns a sorted list from the tuple's items (does not modify tuple).sorted((3, 1, 2)) → [1, 2, 3]
any(tuple)Returns True if at least one element is True.any((0, False, 5)) → True
all(tuple)Returns True if all elements are True.all((1, 2, 3)) → True


Example:

# Define a tuple
my_tuple = (4, 7, 1, 9, 0)
print("Tuple:", my_tuple)

# Length of tuple
print("Length:", len(my_tuple))

# Maximum value
print("Max value:", max(my_tuple))

# Minimum value
print("Min value:", min(my_tuple))

# Sum of elements
print("Sum:", sum(my_tuple))

# Sorted version (returns a list)
print("Sorted:", sorted(my_tuple))

# Convert a list to tuple
my_list = [10, 20, 30]
converted = tuple(my_list)
print("Converted from list:", converted)

# Use of any() and all()
bool_tuple = (1, True, 0)
print("Any true?", any(bool_tuple))   # True, because 1 or True present
print("All true?", all(bool_tuple))   # False, because 0 is False

Output:
Tuple: (4, 7, 1, 9, 0)
Length: 5
Max value: 9
Min value: 0
Sum: 21
Sorted: [0, 1, 4, 7, 9]
Converted from list: (10, 20, 30)
Any true? True
All true? False

Set

  • In Python, a set is a collection of unordered and unindexed elements.
  • Sets can store elements of different data types (integers, strings, floats, etc.).
  • Sets are similar to lists and tuples, but they do not maintain order and do not allow duplicates.
  • The elements of a set are immutable (cannot be changed), but the set itself is mutable (you can add or remove elements).
  • Sets are defined using curly braces {} and elements are separated by commas.
  • Python implements the set data type using the built-in set class.
  • Sets do not allow duplicate values. Any repeated item is automatically removed.
  • Sets are unordered, so items appear in random order and cannot be accessed by index.
  • Sets are useful when you need to store unique items and perform mathematical set operations (like union, intersection, difference).

Creating a Set in Python

  • set is created using curly braces {} or the set() constructor.

  • Elements inside a set must be separated by commas.

  • Sets automatically remove duplicate values.

  • You can store elements of different data types in a single set.

Method 1: Using Curly Braces

# Creating a set with curly braces
my_set = {1, 2, 3, 4}
print(my_set)  

Output: {1, 2, 3, 4}

Method 2: Using the set() Constructor

# Creating a set from a list
my_list = [1, 2, 2, 3]
my_set = set(my_list)
print(my_set)  

Output: {1, 2, 3}

 Accessing Set Elements

Sets are unordered and unindexed, so you cannot access elements using an index like you do with lists or tuples.

my_set = {10, 20, 30}
print(my_set[0])  #  This will raise a TypeError

To access elements, you generally use a loop.

my_set = {'apple', 'banana', 'cherry'}
for item in my_set:
    print(item)

Set Operations

Adding elements to a set

1. add()

Adds a single element.

my_set = {1, 2}
my_set.add(3)         

Output:
{1, 2, 3}

2. update()

Adds multiple elements (from any iterable like list, tuple, or another set).

my_set = {1, 2}
my_set.update([3, 4])     # {1, 2, 3, 4}
my_set.update((5, 6))     # {1, 2, 3, 4, 5, 6}
my_set.update({7, 8})     # {1, 2, 3, 4, 5, 6, 7, 8}

Removing elements from set

1. remove()

Removes a specific element. Raises an error if the element doesn’t exist.

my_set = {1, 2, 3}
my_set.remove(2)     # {1, 3}
my_set.remove(10)  #  KeyError

2. discard()

Removes a specific element. Does nothing if the element doesn’t exist.

my_set = {1, 2, 3}
my_set.discard(3)    # {1, 2}
my_set.discard(10)   # No error

3. pop()

Removes and returns a random element (since sets are unordered).

my_set = {1, 2, 3}
removed = my_set.pop()
print(removed)       # Could be 1, 2, or 3

4. clear()

Removes all elements from the set.

my_set = {1, 2, 3}
my_set.clear()       # my_set becomes set()

OperationSymbolPython MethodMeaningExample Result
Unionunion()All elements in A or B{1, 2, 3, 4, 5, 6}
Intersectionintersection()Elements in both A and B{3, 4}
Difference (A - B)difference()Elements in A but not in B{1, 2}
Symmetric Differencesymmetric_difference()Elements in A or B but not both{1, 2, 5, 6}

Example:
# Define two example sets
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}

print("Set A:", A)
print("Set B:", B)

# Union
union_set = A.union(B)
print("Union (A ∪ B):", union_set)

# Intersection
intersection_set = A.intersection(B)
print("Intersection (A ∩ B):", intersection_set)

# Difference (A - B)
difference_set = A.difference(B)
print("Difference (A - B):", difference_set)

# Symmetric Difference
sym_diff_set = A.symmetric_difference(B)
print("Symmetric Difference (A △ B):", sym_diff_set)

Output:
Set A: {1, 2, 3, 4}
Set B: {3, 4, 5, 6}
Union (A ∪ B): {1, 2, 3, 4, 5, 6}
Intersection (A ∩ B): {3, 4}
Difference (A - B): {1, 2}
Symmetric Difference (A △ B): {1, 2, 5, 6}

Dictionary

  • In Python, a dictionary is a collection of elements where each element is a pair of key and value.
  •  In Python, the dictionary data type (data structure) has implemented with a class known as dict. 
  • All the elements of a dictionary must be enclosed in curly braces, each element must be separated with a comma symbol, and every pair of key and value must be separated with colon ( : ) symbol.
Creating Dictionary 
  • Creating a dictionary is as simple as placing items inside curly braces {} separated by commas.
  • An item has a key and a corresponding value that is expressed as a pair (key: value).
 Example: 
# 1. Empty dictionary
my_dict1 = {}
print("1. Empty dictionary:", my_dict1)

# 2. Dictionary with integer keys
my_dict2 = {1: 'apple', 2: 'ball'}
print("2. Dictionary with integer keys:", my_dict2)

# 3. Dictionary with mixed keys
my_dict3 = {'name': 'John', 1: [2, 4, 3]}
print("3. Dictionary with mixed keys:", my_dict3)

# 4. Using dict() with another dictionary
my_dict4 = dict({1: 'apple', 2: 'ball'})
print("4. Using dict() with a dictionary:", my_dict4)

# 5. Using dict() with list of tuples (sequence of key-value pairs)
my_dict5 = dict([(1, 'apple'), (2, 'ball')])
print("5. Using dict() with list of tuples:", my_dict5)

Output:

1. Empty dictionary: {}
2. Dictionary with integer keys: {1: 'apple', 2: 'ball'}
3. Dictionary with mixed keys: {'name': 'John', 1: [2, 4, 3]}
4. Using dict() with a dictionary: {1: 'apple', 2: 'ball'}
5. Using dict() with list of tuples: {1: 'apple', 2: 'ball'}

Accessing Elements from Dictionary

In Python, the dictionary elements are organized based on the keys. So, we can access using the key of a value in the dictionary. Python provides the following ways to access the elements of a dictionary.
  • Using Key as index - The elements of a dictionary can be accessed using the key as an index.
  • get( key ) - This method returns the value associated with the given key in the dictionary.
  • Accessing the whole dictionary - In Python, we use the name of the dictionary to access the whole dictionary.
  • items( ) - This is a built-in method used to access all the elements of a dictionary in the form of a list of key-value pair.
  • keys( ) - This is a built-in method used to access all the keys in a dictionary in the form of a list.
  • values( ) - This is a built-in method used to access all the values in a dictionary in the form of a list.
# Creating a dictionary with student details
student_dictionary = {
    'rollNo': 1,
    'name': 'Nani',
    'department': 'BSC',
    'year': 2
}

# 1. Displaying the type of the dictionary
print(type(student_dictionary))

# 2. Accessing a value using the key as an index
print(student_dictionary['rollNo'])

# 3. Accessing a value using the get() method
print(student_dictionary.get('name'))

# 4. Accessing the whole dictionary
print(student_dictionary)

# 5. Accessing all key-value pairs using items() method
print(student_dictionary.items())

# 6. Accessing all keys using keys() method
print(student_dictionary.keys())

# 7. Accessing all values using values() method
print(student_dictionary.values())

Output:
  1. <class 'dict'>
  2. 1
  3. Nani
  4. {'rollNo': 1, 'name': 'Nani', 'department': 'BSC', 'year': 2}
  5. dict_items([('rollNo', 1), ('name', 'Nani'), ('department', 'BSC'), ('year', 2)])
  6. dict_keys(['rollNo', 'name', 'department', 'year'])
  7. dict_values([1, 'Nani', 'BSC', 2])

Operations in Dictionary

Dictionaries in Python allow us to perform various operations such as addingupdatingdeleting, and more.
  • Adding elements - To add a new key-value pair, simply assign a value to a new key. 
  • Updating elements - If the key already exists, assigning a new value will update it.
Removing elements 
  • pop( key ) - This method removes the element with a specified key from the dictionary.
  • popitem( ) - This method removes the last element from the dictionary.
  • clear( ) - This method removes all the elements from the dictionary. That means the clear( ) method make the dictionary empty. This method returns the None value.
  • del keyword with dict[key] - This keyword deletes the element with the specified key from the dictionary. Once the del keyword has used on a dictionary, we can not access it in the rest of the code.
  • del keyword - This keyword deletes the dictionary completely. Once the del keyword has used on a dictionary, we can not access it in the rest of the code.

Example:

# Creating a dictionary with student details
student_dictionary = {
    'rollNo': 1,
    'name': 'Ram',
    'department': 'CSE',
    'year': 2,
    'section': 'A',
    'percentage': 80.5
}

# Displaying the original dictionary
print(f'Dictionary is {student_dictionary}')

# Updating the value of the 'name' key to 'Swathi'
student_dictionary['name'] = 'Swathi'

# Removing the element with key 'year' using pop()
student_dictionary.pop('year')
print(f'The dictionary after removing element with key "year":\n{student_dictionary}')

# Removing the last inserted item using popitem()
student_dictionary.popitem()
print(f'The dictionary after popitem():\n{student_dictionary}')

# Deleting the key 'section' using del
del student_dictionary['section']
print(f'The dictionary after deleting "section":\n{student_dictionary}')

# Clearing all elements from the dictionary using clear()
student_dictionary.clear()
print(f'The dictionary after clear():\n{student_dictionary}')

# Deleting the dictionary completely
del student_dictionary

# Uncommenting the line below would raise an error because the dictionary no longer exists
# print(f'The dictionary after del:\n{student_dictionary}')  # ❌ This line causes an error

Output:

Dictionary is {'rollNo': 1, 'name': 'Ram', 'department': 'CSE', 'year': 2, 'section': 'A', 'percentage': 80.5}
The dictionary after removing element with key "year":
{'rollNo': 1, 'name': 'Swathi', 'department': 'CSE', 'section': 'A', 'percentage': 80.5}
The dictionary after popitem():
{'rollNo': 1, 'name': 'Swathi', 'department': 'CSE', 'section': 'A'}
The dictionary after deleting "section":
{'rollNo': 1, 'name': 'Swathi', 'department': 'CSE'}
The dictionary after clear():
{}

Comments

Popular posts from this blog

Getting started with Python, Strings

FUNCTIONS, PYTHON OOPS AND EXCEPTION HANDLING

Numpy and Data Handling using Pandas