Python Data Types & Data Structures
Python Data Types & Data Structures
# Floating Point
b = 2.5
print(type(b)) # Output: <class 'float'>
# Complex Number
y = 2 + 3j
print(type(y)) # Output: <class 'complex'>
print(y.real) # Output: 2.0
print(y.imag) # Output: 3.0
6.3.2 Strings
• A String is a sequence of characters. Strings can be of any length,
including empty strings. Strings are immutable in Python.
# Creating a string
s = "Hello World!"
print(type(s)) # Output: <class 'str'>
# String concatenation
t = "This is a sample program."
print(s + " " + t) # Output: Hello World! This is a sample program.
• # Accessing sub-strings
• print(s[6:]) # Output: World!
• print(s[:5]) # Output: Hello
6.3.3 Lists
A List is a compound data type that stores multiple items, which can be of different types. Lists are mutable, so
elements can be added, removed, or modified.
# Creating a list
fruits = ["apple", "orange", "banana", "mango"]
print(type(fruits)) # Output: <class 'list'>
print(len(fruits)) # Output: 4
# Accessing elements
print(fruits[1]) # Output: orange
# Creating a tuple
fruits = ("apple", "mango", "banana", "pineapple")
print(type(fruits)) # Output: <class 'tuple'>
print(len(fruits)) # Output: 4
# Accessing elements
print(fruits[0]) # Output: apple
# Combining tuples
vegetables = ("potato", "carrot", "onion", "radish")
eatables = fruits + vegetables
print(eatables) # Output: ('apple', 'mango', 'banana', 'pineapple', 'potato', 'carrot', 'onion', 'radish')
6.3.5 Dictionaries
A Dictionary is a mapping data type that associates keys with values. Keys are unique, and values
can be of any data type. Dictionaries are mutable.
# Creating a dictionary
student = {"name": "Mary", "id": "8776", "major": "CS"}
print(type(student)) # Output: <class 'dict'>
print(len(student)) # Output: 3
# Convert to string
a = 100
str_a = str(a)
print(str_a) # Output: '100'
# Convert to integer
b = "2013"
int_b = int(b)
print(int_b) # Output: 2013
# Convert to float
float_b = float(b)
print(float_b) # Output: 2013.0
• # Convert to list
• s = "apple"
• list_s = list(s)
• print(list_s) # Output: ['a', 'p', 'p', 'l', 'e']