-4

I was stucked in 2D list something like ((A,B),(C,D),(E,F),(G,H)) to convert it to 1D [A,B,C,D,E,F,G,H]. I have searched and found the below loop which worked.

a = ((A,B),(C,D),(E,F),(G,H))
b = [i for j in a for i in j]

But I am not able to understand this loop. Please help me in understanding the same.

dzang
  • 1,695
  • 1
  • 7
  • 17
  • The term in Python is "List Comprehension". It is well documented. – dfundako Sep 21 '20 at 15:06
  • Welcome to Stack Overflow! Sounds like you need to go through a python tutorial or talk to an instructor about list comprehensions. Stack Overflow is neither of those, and questions asking for tutorials are [off-topic](/help/on-topic). – Pranav Hosangadi Sep 21 '20 at 15:07
  • The keyword is [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions). The code you posted is roughly equivalent to: `b=[]; for j in a: for i in j: b.append(i)` – Stef Sep 21 '20 at 15:09
  • 1
    Your code is not valid python code. Try to provide runable code, because nobody wants to edit your code to find a solution. – Michael Szczesny Sep 21 '20 at 15:09
  • Does this answer your question? [What does "list comprehension" mean? How does it work and how can I use it?](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it) – dzang Sep 21 '20 at 15:19
  • Yes. Thanks for your help. I am new to Stack Overflow. Didn't knew where to ask questions so posted here. Thanks all for your responses. – Rajat Bhardwaj Sep 21 '20 at 15:23

1 Answers1

1

That's equivalent to writing:

b = []
for j in a:  # j will be a tuple like (A, B)
    for i in j:  # i will be an element of j, like A and then B
        b.append(i)  # append single elements of evert tuple to the new list

As mentioned in the comments, that's a 'List Comprehension', it's a fast and compact way of writing for loops that creates lists.

Consider checking out https://stackoverflow.com/help/how-to-ask as a guideline for asking questions

dzang
  • 1,695
  • 1
  • 7
  • 17
  • 1
    Might as well add the link to the [documentation on list comprehensions](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions) to this answer. – Stef Sep 21 '20 at 15:12