List Conversion (e.g., to/from strings or other collections) (longest content) in Python Code
List conversion in Python involves transforming lists to and from other data types, such as strings, tuples, sets, dictionaries, and more. Here's a comprehensive guide to different types of list conversions:
1. List to String
Using join()
Python Code
# List of strings
list_of_strings = ["apple", "banana", "cherry"]
string_result = ", ".join(list_of_strings)
print(string_result) # Output: "apple, banana, cherry"
Using List Comprehension
Python Code
# List of integers
list_of_integers = [1, 2, 3]
string_result = ' '.join([str(i) for i in list_of_integers])
print(string_result) # Output: "1 2 3"
2. String to List
Using split()
Python Code
string = "apple, banana, cherry"
list_result = string.split(", ")
print(list_result) # Output: ['apple', 'banana', 'cherry']
Using List Comprehension
Python Code
string = "123"
list_result = [char for char in string]
print(list_result) # Output: ['1', '2', '3']
3. List to Tuple
Python Code
list_data = [1, 2, 3]
tuple_result = tuple(list_data)
print(tuple_result) # Output: (1, 2, 3)
4. Tuple to List
Python Code
tuple_data = (1, 2, 3)
list_result = list(tuple_data)
print(list_result) # Output: [1, 2, 3]
5. List to Set
Python Code
list_data = [1, 2, 3, 1]
set_result = set(list_data)
print(set_result) # Output: {1, 2, 3}
6. Set to List
Python Code
set_data = {1, 2, 3}
list_result = list(set_data)
print(list_result) # Output: [1, 2, 3]
7. List to Dictionary
Using enumerate()
Python Code
list_data = ['a', 'b', 'c']
dict_result = dict(enumerate(list_data))
print(dict_result) # Output: {0: 'a', 1: 'b', 2: 'c'}
Using Dictionary Comprehension
Python Code
list_data = ['a', 'b', 'c']
dict_result = {i: value for i, value in enumerate(list_data)}
print(dict_result) # Output: {0: 'a', 1: 'b', 2: 'c'}
8. Dictionary to List
Keys
Python Code
dict_data = {0: 'a', 1: 'b', 2: 'c'}
keys_list = list(dict_data.keys())
print(keys_list) # Output: [0, 1, 2]
Values
Python Code
values_list = list(dict_data.values())
print(values_list) # Output: ['a', 'b', 'c']
Items
Python Code
items_list = list(dict_data.items())
print(items_list) # Output: [(0, 'a'), (1, 'b'), (2, 'c')]
9. List to JSON
Using json.dumps()
Python Code
import json
list_data = ["apple", "banana", "cherry"]
json_result = json.dumps(list_data)
print(json_result) # Output: '["apple", "banana", "cherry"]'
10. JSON to List
Using json.loads()
Python Code
json_data = '["apple", "banana", "cherry"]'
list_result = json.loads(json_data)
print(list_result) # Output: ["apple", "banana", "cherry"]
11. List to Numpy Array
Using numpy.array()
Python Code
import numpy as np
list_data = [1, 2, 3]
array_result = np.array(list_data)
print(array_result) # Output: array([1, 2, 3])
12. Numpy Array to List
Using tolist()
Python Code
array_data = np.array([1, 2, 3])
list_result = array_data.tolist()
print(list_result) # Output: [1, 2, 3]
13. List to Pandas Series
Using pd.Series()
Python Code
import pandas as pd
list_data = [1, 2, 3]
series_result = pd.Series(list_data)
print(series_result)
# Output:
# 0 1
# 1 2
# 2 3
# dtype: int64
14. Pandas Series to List
Using tolist()
Python Code
series_data = pd.Series([1, 2, 3])
list_result = series_data.tolist()
print(list_result) # Output: [1, 2, 3]
15. Flattening a Nested List
Using List Comprehension
Python Code
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flattened_list = [item for sublist in nested_list for item in sublist]
print(flattened_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8]
Using itertools.chain
Python Code
import itertools
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flattened_list = list(itertools.chain.from_iterable(nested_list))
print(flattened_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8]
16. List to DataFrame
Using pd.DataFrame()
Python Code
list_data = [[1, 'John'], [2, 'Jane'], [3, 'Doe']]
df_result = pd.DataFrame(list_data, columns=['ID', 'Name'])
print(df_result)
# Output:
# ID Name
# 0 1 John
# 1 2 Jane
# 2 3 Doe
17. DataFrame to List
Using values.tolist()
Python Code
df_data = pd.DataFrame({'ID': [1, 2, 3], 'Name': ['John', 'Jane', 'Doe']})
list_result = df_data.values.tolist()
print(list_result) # Output: [[1, 'John'], [2, 'Jane'], [3, 'Doe']]
Using to_dict()
Python Code
list_result = df_data.to_dict(orient='records')
print(list_result) # Output: [{'ID': 1, 'Name': 'John'}, {'ID': 2, 'Name': 'Jane'}, {'ID': 3, 'Name': 'Doe'}]
These examples cover the most common list conversions in Python. Depending on your use case, you might need to adjust the approach slightly, but these should serve as a solid foundation for understanding how to work with lists and other data types.
Top of Form