Python_Data_Types
Python_Data_Types
List
A list is an ordered, mutable (changeable) collection that can hold a variety of data types.
Lists are defined using square brackets [].
Example:
# Accessing elements
print(my_list[1]) # Output: 2
# Adding elements
my_list.append("orange")
print(my_list) # Output: [1, 2, 3, 'apple', True, 'orange']
Dictionary
A dictionary is an unordered, mutable collection of key-value pairs. Dictionaries are defined
using curly braces {}.
Example:
# Accessing values
print(my_dict["name"]) # Output: Alice
Set
A set is an unordered, mutable collection of unique elements. Sets are defined using curly
braces {} or the set() function.
Example:
my_set = {1, 2, 3, 4, 4, 5}
print(my_set) # Output: {1, 2, 3, 4, 5} (duplicates are removed)
# Adding elements
my_set.add(6)
print(my_set) # Output: {1, 2, 3, 4, 5, 6}
Integer (int)
Integers are whole numbers, positive or negative, without decimals.
Example:
my_int = 42
print(my_int) # Output: 42
# Arithmetic operations
print(my_int + 8) # Output: 50
String
A string is a sequence of characters enclosed in single ' or double " quotes.
Example:
# Accessing characters
print(my_string[0]) # Output: H
# String concatenation
print(my_string + " How are you?") # Output: Hello, Python! How are you?
Tuple
A tuple is an ordered, immutable collection. Tuples are defined using parentheses ().
Example:
# Accessing elements
print(my_tuple[1]) # Output: 2
# Tuples are immutable, so we can't modify elements
# my_tuple[0] = 10 # This will raise an error
Key Differences
Type Ordered? Mutable? Duplicates Allowed?
List Yes Yes Yes
Dictionary No Yes No (for keys)
Set No Yes No
Integer N/A Immutable N/A
String Yes Immutable Yes
Tuple Yes No Yes