Python supports several core data types, each with distinct characteristics:
- Numeric Types: int, float, bool, complex
- Strings: Enclosed in single or double quotes, using ASCII characters
- Lists: Ordered, mutable collections of items separated by commas
- Tuples: Ordered, immutable collections enclosed in parentheses
- Dictionaries: Key-value pairs enclosed in curly braces
- Sets: Unordered collections of unique elements
Type Conversion Methods
1. Numeric Conversions
Convert between numeric types using built-in functions:
-
int(): Converts strings to integers if possible ``` print(int("42")) # Output: 42
-
float(): Converts strings to floating-point numbers ``` print(float("-3.14")) # Output: -3.14
2. String Conversions
Convert any data type to a string representation:
-
str(): Creates string objects from other data types ``` numbers = [1, 2, 3] print(str(numbers)) # Output: "[1, 2, 3]" print(type(str(numbers))) # Output: <class 'str'>
3. List Conversion
Create lists from iterable objects:
-
list(): Converts dictionaries to list of keys, and strings to character lists ``` person = {'name': 'Alice', 'age': 30} print(list(person)) # Output: ['name', 'age']
text = "hello" print(list(text)) # Output: ['h', 'e', 'l', 'l', 'o']
4. Tuple Conversion
Create immutable tuples from iterable objects:
-
tuple(): Converts lists or strings to tuples ``` my_list = [1, 2, 3] print(tuple(my_list)) # Output: (1, 2, 3)
5. Set Conversion
Create sets from iterable objects, ensuring all elements are immutable:
-
set(): Converts lists to sets, removing duplicates ``` my_list = [1, 2, 2, 3, 4, 4] print(set(my_list)) # Output: {1, 2, 3, 4}
Attempting to create a set with mutable elements will raise an error
nested_list = [1, 2, [3, 4]] print(set(nested_list)) # TypeError: unhashable type: 'list'
6. Dictionary Conversion
Create dictionaries using two methods:
-
dict() with keyword arguments:``` person = dict(name="John", age=30) print(person) # Output: {'name': 'John', 'age': 30}
-
dict() from a list of key-value pairs:``` items = [("id", 1), ("email", "john@example.com")] print(dict(items)) # Output: {'id': 1, 'email': 'john@example.com'}