Categories

Dec 22, 2019 in Python
Q: How To Convert A List Into Other Data Types?

1 Answer

Dec 22, 2019

Sometimes, we don’t use lists as is. Instead, we have to convert them to other types.

Turn A List Into A String.

We can use the ”.join() method which combines all elements into one and returns as a string.

weekdays = ['sun','mon','tue','wed','thu','fri','sat']

listAsString = ' '.join(weekdays)

print(listAsString)

#output: sun mon tue wed thu fri sat

Turn A List Into A Tuple.

Call Python’s tuple() function for converting a list into a tuple.

This function takes the list as its argument.

But remember, we can’t change the list after turning it into a tuple because it becomes immutable.

weekdays = ['sun','mon','tue','wed','thu','fri','sat']

listAsTuple = tuple(weekdays)

print(listAsTuple)

#output: ('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat')

Turn A List Into A Set.

Converting a list to a set poses two side-effects.

Set doesn’t allow duplicate entries so that the conversion will remove any such item.

A set is an ordered collection, so the order of list items would also change.

However, we can use the set() function to convert a list into a Set.

weekdays = ['sun','mon','tue','wed','thu','fri','sat','sun','tue']

listAsSet = set(weekdays)

print(listAsSet)

#output: set(['wed', 'sun', 'thu', 'tue', 'mon', 'fri', 'sat'])

Turn A List Into A Dictionary.

In a dictionary, each item represents a key-value pair. So converting a list isn’t as straightforward as it were for other data types.

However, we can achieve the conversion by breaking the list into a set of pairs and then call the zip() function to return them as tuples.

Passing the tuples into the dict() function would finally turn them into a dictionary.

weekdays = ['sun','mon','tue','wed','thu','fri']

listAsDict = dict(zip(weekdays[0::2], weekdays[1::2]))

print(listAsDict)

#output: {'sun': 'mon', 'thu': 'fri', 'tue': 'wed'}

Click here to read more about Python
Click here to read more about Insurance

Related questions

Madanswer
Jun 28 in Python
Nov 4 in JSON
Feb 15 in JAVA
...