Recently, I have been trying to join elements present inside an array, which itself is present inside an another array (say array1). Using generator expressions I was able to join the elements successfully. The code looks like this:
array1=[[0,2],[1,1,1],[3,11,1],[2,4,0]] #Driver list
result=[] #Array where the **value** gets appended
for i in x: #for loop to iterate inside array1
value='.'join(str(j) for j in i) #join() using generator expression
result.append(value)
print(result)
The output we get is:
['0.2', '1.1.1', '3.11.1', '2.4.0']
I tried to code the same using nested for loop, and before running the program, I thought, it should provide the same output as above.
:The code involving join()
using nested for loop
is:
array1=[[0,2],[1,1,1],[3,11,1],[2,4,0]] #Driver list
result=[]
for i in array1: #Nested for loop
for j in i:
value='.'.join(str(j))
result.append(value)
print(result)
But to my surprise, the output I got was
['0', '2', '1', '1', '1', '3', '1.1', '1', '2', '4', '0']
I copied both the codes and ran it in python visualize to get an idea about the values of i
and j
, but no clarity was obtained. According to my thinking, both the codes must work in same way.
Is there any conceptual difference between the codes I have written? If so, what options do I have, to make the second code ( join() using nested for loop ) to produce the same output as in the first case.
join is taking a list and turning it into a string with the string, in the beginning, separates between values in the list so if you give join just int or string it will return the same as doing str(value). for example:
".".join(5) will give: "5"
".".join([5,8]) will give: "5.8"
So Yes, In the first option, you use one for loop so you get into i: [0,2], [1,1,1] ... and in the join, you do something called list comprehension so it stays the same list but in the second solution you get into j: 0,2,1,1,1 .... and as we mentioned before there is a difference between join that get value as parameter and not list so that is the reason you get this output, I would recommend you to print i and j to understand what you put in the join as parameter:)