Comprehension list | Sololearn: Learn to code for FREE!


Comprehension list

I would like to get example contains Comprehension list with join() function for learning

2/15/2018 12:56:16 AM

Mohamed Rashidey Hasan

1 Answer

New Answer


# List comprehension is a shorthand way to initialize a list, as you can do through more explicit looping: myList = [ chr(i+97) for i in range(5) ] # is equivalent to: myList = [ ] for i in range(5): myList.append(chr(i+97)) # obviously, expression used in list comprehension could be more complex ^^ # on the other hand, the string join() method (in other languages join() is often a method of array/list objects) concatenate all items of a list to a string with a separator (or not), but in Python, you must be aware that you cannot implicitly append other type than string to string: # previous myList is now equal to: [ 'a', 'b', 'c', 'd', 'e' ] myString = ':'.join(myList) # 'a:b:c:d:e' myIntList = [ 1, 2, 3 ] # myString = ':'.join(myIntList) # error myString = ':'.join([ str(value) for value in myIntList ]) # '1:2:3'