PYTHON Tutorial



DATA STRUCTURE IN PYTHON


📊 Data Structures in Python

Python provides several built-in data structures, which allow you to store and manipulate data in different ways. The main data structures in Python are:

🔸 Lists

A list is an ordered collection of items, which can be of different types (e.g., integers, strings, etc.). Lists are mutable, meaning their elements can be changed after the list is created.

# List Example
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"  # Modify item
print(fruits)
# Output: ['apple', 'blueberry', 'cherry']
  

🔸 Tuples

A tuple is an ordered collection of items, similar to a list, but it is immutable (i.e., its values cannot be changed once created).

# Tuple Example
coordinates = (4, 5)
print(coordinates[0])  # Access item
# Output: 4
  

🔸 Dictionaries

A dictionary is an unordered collection of key-value pairs. Keys must be unique, while values can be of any data type.

# Dictionary Example
person = {"name": "Alice", "age": 25}
print(person["name"])  # Access value by key
# Output: Alice
  

🔸 Sets

A set is an unordered collection of unique elements. It does not allow duplicate values.

# Set Example
unique_numbers = {1, 2, 3, 4}
unique_numbers.add(5)  # Add new item
unique_numbers.remove(2)  # Remove item
print(unique_numbers)
# Output: {1, 3, 4, 5}
  

🔸 Arrays

Although Python does not have a built-in array data type, arrays can be created using the array module. Unlike lists, arrays require elements to be of the same type.

# Array Example
import array
arr = array.array('i', [1, 2, 3, 4])  # 'i' is the type code for integers
print(arr)
# Output: array('i', [1, 2, 3, 4])
  
💡 Note: - Lists and tuples are ordered, while sets and dictionaries are unordered. - Lists and dictionaries are mutable, while tuples and sets are immutable in certain ways.

🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review