Python Forum
Comprehending a list comprehension!
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Comprehending a list comprehension!
#1
I have been given some example code that captures BLE broadcasts from beacons but there's a line that is really confusing me:

data = [b for b in device.data]
device.data is a list that contains BLE broadcast data from the bluetooth.get_adv() MicroPython function. It can hold up to 16 devices.

I just don't understand the syntax. b is not used anywhere and I don't get what b for b is actually doing, especially since it isn't defined anywhere.

I think this is a 'list comprehension' but the explanations I have found are addling my noodle. How would this expand into a normal, sane 'for loop'?
Reply
#2
If device.data is a list, data = [b for b in device.data] is meaningless. It's the same as data = device.data. Anyway! The whole [b for b in device.data] means "append to data an element ( b) for any element in the list ( device.data ). It the same as:

for b in device.data:
    data.append(b)
See https://python-forum.io/Thread-Comprehen...xpressions
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
(Oct-30-2017, 10:51 AM)wavic Wrote: If device.data is a list, data = [b for b in device.data] is meaningless. It's the same as data = device.data.

That is not true. List is mutable, thus is you just do data = device.data change in data would affect also device.data and vice versa.

>>> my_list = [1, 2, 3]
>>> a_list = [x for x in my_list]
>>> b_list = my_list
>>> my_list[0] = 100
>>> my_list
[100, 2, 3]
>>> a_list # still has the original values
[1, 2, 3]
>>> b_list
[100, 2, 3] # has new value at index 0, same as my_list
>>>
an alternative to list comprehension for creating a copy would be list slicing
data = device.data[::]
Reply
#4
You are right. data = device.data will create just another pointer to the same address.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#5
Quote:I just don't understand the syntax. b is not used anywhere and I don't get what b for b is actually doing, especially since it isn't defined anywhere.

list comps can get unwieldy to the point of doing more harm than good, but this is the most simple.


[b for b in device.data]
There are two parts here. The second is the actual for loop header, the first is what is being put into the list on each iteration. Assuming device.data was a list of stringed ints, you could convert these by modifying the first section as such
[int(b) for b in device.data]
The result would be a list of ints, instead of strings.

On the same token if you wanted to restrict what is in the new list
[int(b) for b in device.data if b.startswith('o')]
which would look like
[int(b) for b in device.data if b.startswith('o')]
This would be the equivalent of adding an if condition into the for loops block. This would create a third section in the list comp that you would have to identify.
The first section is what is being added to the list, the second is the for loop header, and the 3rd is the restrictions. You could kind of read it from section 2, section 3, then section 1.
This would be the drawn out for loop
lst = []
for b in device.data:
    if b.startswith('o'):
        lst.append(int(b))
You can make it more complicated, but at times depending on how much more complicated, it might not be worth it as it takes too long for humans to decipher.

An example of the same as previous, but one you might want to split out into a regular for loop
[x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]

You can of course split it out within, but then at that point is it worth it?

all_posts_uuid_query = self.db.query(schema.allPostsUuid)
all_posts_uuid_list = all_posts_uuid_query.execute(timeout=20)
all_uuid_list = [
    x.id 
    for x in all_posts_uuid_list 
    if (
        x.type == "post" 
        and 
        not x.deleted  # <-- if you don't care about NULLs / None
    )
]
Recommended Tutorials:
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  List Comprehension Issue johnywhy 5 546 Jan-14-2024, 07:58 AM
Last Post: Pedroski55
Question mypy unable to analyse types of tuple elements in a list comprehension tomciodev 1 495 Oct-17-2023, 09:46 AM
Last Post: tomciodev
  Using list comprehension with 'yield' in function tester_V 5 1,265 Apr-02-2023, 06:31 PM
Last Post: tester_V
  list comprehension 3lnyn0 4 1,426 Jul-12-2022, 09:49 AM
Last Post: DeaD_EyE
  List comprehension used differently coder_sw99 3 1,740 Oct-03-2021, 04:12 PM
Last Post: coder_sw99
  How to invoke a function with return statement in list comprehension? maiya 4 2,868 Jul-17-2021, 04:30 PM
Last Post: maiya
  List comprehension and Lambda cametan 2 2,257 Jun-08-2021, 08:29 AM
Last Post: cametan
  What is the difference between a generator and a list comprehension? Pedroski55 2 2,234 Jan-02-2021, 04:24 AM
Last Post: Pedroski55
  For Loop with List Comprehension muzikman 25 6,710 Dec-18-2020, 10:45 PM
Last Post: muzikman
  Using recursion instead of for loops / list comprehension Drone4four 4 3,162 Oct-10-2020, 05:53 AM
Last Post: ndc85430

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020