Python: how to form the correct list
Question:
This is my data looks like
my_list = [('Australia',), ('Europe',)]
I need to remove the comma "," after every element.
new_list = [('Australia'), ('Europe')]
I can achieve this using a loop and extracting one element at a time and replacing it. Is there a better way to achieve the same. Thank you
Answers:
That comma, indicates that you have a tuple. If you want to not have that comma, you can change tuples to lists:
new_list = [list(country) for country in my_list]
It gives You:
[['Australia'], ['Europe']]
my_list = [('Australia',), ('Europe',)]
# lambda create a function and returns first value of x
# function map takes a function and list
# it puts every value of list to function
country = list(map(lambda x: x[0], my_list))
print(country)
This is my data looks like
my_list = [('Australia',), ('Europe',)]
I need to remove the comma "," after every element.
new_list = [('Australia'), ('Europe')]
I can achieve this using a loop and extracting one element at a time and replacing it. Is there a better way to achieve the same. Thank you
That comma, indicates that you have a tuple. If you want to not have that comma, you can change tuples to lists:
new_list = [list(country) for country in my_list]
It gives You:
[['Australia'], ['Europe']]
my_list = [('Australia',), ('Europe',)]
# lambda create a function and returns first value of x
# function map takes a function and list
# it puts every value of list to function
country = list(map(lambda x: x[0], my_list))
print(country)