- What are Lists
- What are Strings
- Convert List to Strings
- Convert List of integers to a single integer
- Convert String to Lists
- Convert String to list of characters
What are Lists?
If you are familiar with the C programming language, then you might have heard about arrays. Lists are pretty much like arrays except that they can contain any data type, unlike arrays. A list is a collection of objects that are ordered. Also, each element in the list is indexed according to a definite sequence and the indexing of a list is done with 0 being the first index.
The list is a ‘Collection Datatype’ that can contain integers, strings, or other lists too. Lists are mutable, hence, they can be changed even after their creation. Also, note that lists can contain duplicate entries, unlike sets. Python lists can be created in the following way:
EmptyList= #EmptyList listOfnumbers=[1,3,56,78] #List of numbers listOfObjects=[1,"anything",["lists","in","lists"],2.5] # List containing different data types print(EmptyList) print(listOfnumbers) print(listOfObjects)
What are ‘Strings’?
So, what exactly are strings? Strings are one of the data types in Python and can be defined as a sequence of characters. There is a built-in class ‘str’ for handling a Python string. Creating strings is as simple as assigning a value to a variable. For example −
first_name='''Ted ''' middle_name="Evelen "#commonly used method last_name='Mosby'#commonly used method print(first_name,middle_name,last_name)
As can be seen in the example above, there are three ways in which we can create a string. Although double quotes and single quotes are more often used as compared to the triple quotes, what if the string itself contains a single quote or double-quotes. Let us find out in the example below.
string_1="Hello "Python" "
string_1='Hello "Python"' print(string_1)
string_2='Let's go to the park'
string_2="Let's go to the park" print(string_2)
string_3='''Let's go the "PARK"''' print(string_3)
In the above example, we learned how to avoid such errors, now moving on to the question “how to convert a list to a string?”
Convert List to String
Several methods can be used to convert a list to a string.
By using the in-built method of python .join()
Name=["Ted","Evelen","Mosby"] print(" ".join(Name))#used a space to separate list elements here. Students=["Barney","Robin","Lily"] print("\n".join(Students))
NOTE: If the list contains any non-string element, the above method does not work unless we use map() function to convert all elements to a string first. Let’s see an example:
test_list=["I","have",2,"numbers","and",8,"words","in","this","list"] print(" ".join(map(str,test_list)))
Using the str() method
Numbers=[1,56,87,22.3,76] print(str(Numbers)) #Now manipulate the str() to get string of just Numbers print(str(Numbers)[1:-1]) #or we can use strip function to get jsy Numbers print(str(Numbers).strip(''))
Using List comprehension method
test_list=["I","have",2,"numbers","and",8,"words","in","this","list"] listToStr = ' '.join([str(element) for element in test_list ]) print(listToStr)
Convert a list of integers into a single integer
Given a list of integers like [1,2,3], Can we convert it into a single integer, 123? Sure we can.
Let’s find out some methods to do so
Using the join() method of Python
We can use join() method along with the inbuilt method int() in Python. Let us see some examples to understand better.
list_1 = [1, 2, 3] numbers_str = [str(i) for i in list_1] #Using list comprehension print(numbers_str) #Now that the elements have been converted to strings we can use the join method number= int("".join(numbers_str)) #convert final string to integer print(number)
The second method is much more naive and is best suited when we want to just display the number instead of storing it in a variable as shown in method 1. Let us see how to do this:
list_1 = [12, 15, 17] # iterating each element def toNumber(anyList): for i in anyList: print(i, end="") print("")#This print statement by default prints a new line toNumber(list_1) toNumber([1,8,4,99]) #Note that the number is not stored anywhere.
Convert String to List
We can use the in-built function split() to convert a string to list. Let us see some examples:
string_1="Let us convert string to list" print(string_1.split(" "))# Here we specified " " as delimiter #Based on the specified delimiter the list string will be sepatrated string_2="Let*us*convert*string to*list" print(string_2.split())#By default delimiter is space " " print(string_2.split("*"))#Here we specified * as the delimiter
In the last line of output, it can be seen that the element ‘string to’ is not separated. The reason being that the delimiter specified is asterisk ‘*’ not space “ ”.
Convert String to List of characters
As discussed above, String is a sequence of characters. We can convert it to the list of characters using list() built-in function. When converting a string to a list of characters, whitespaces are also treated as characters. Also, if there are leading and trailing whitespaces, they are a part of the list elements too.
Let us see some examples:
string_1=' Great! *^& ' print(list(string_1)) print(list(string_1.strip()))
The strip function is used to leave out all leading and trailing whitespaces but the spaces in the middle are not left out.
This brings us to the end of this article where we have learned how we can convert list to strings and much more. If you wish to learn more about Python and the concepts of Machine Learning, upskill with Great Learning’s PG Program in Machine Learning.