##### Question about the groupby function
 Question about the groupby function new_to_python Silly Frenchman Posts: 39 Threads: 12 Joined: Feb 2020 Reputation: Feb-08-2020, 04:39 AM Hi, I have the following code: ```import itertools first_letter = lambda x: x[0] names = ['Alan', 'Adam', 'Wes', 'Will', 'Albert', 'Steven'] for letter, names in itertools.groupby(names, first_letter): print(letter, list(names))```The program returned: A ['Alan', 'Adam'] W ['Wes', 'Will'] A ['Albert'] S ['Steven'] Anybody knows why it does not return the result like the following? A ['Alan', 'Adam', 'Albert'] W ['Wes', 'Will'] S ['Steven'] Reply Larz60+ aetate et sapientia Posts: 10,510 Threads: 396 Joined: Sep 2016 Reputation: Feb-08-2020, 06:06 AM list needs to be sorted use: ```>>> names = ['Alan', 'Adam', 'Wes', 'Will', 'Albert', 'Steven'] >>> names.sort() >>> for letter, inames in itertools.groupby(names, first_letter): ... print(letter, list(inames)) ... A ['Adam', 'Alan', 'Albert'] S ['Steven'] W ['Wes', 'Will'] >>>```also, you were overwriting names result: Reply Posts: 1,756 Threads: 8 Joined: Jun 2018 Reputation: Feb-08-2020, 06:37 AM (Feb-08-2020, 04:39 AM)new_to_python Wrote: Anybody knows why it does not return the result like the following? A ['Alan', 'Adam', 'Albert'] W ['Wes', 'Will'] S ['Steven'] In Python interactive interpreter type `>>> help(itertools.groupby)` (note the part which says : returns consecutive keys and groups from the iterable). ```>>> help(itertools.groupby) class groupby(builtins.object) | groupby(iterable, key=None) | | make an iterator that returns consecutive keys and groups from the iterable | | iterable | Elements to divide into groups according to the key function. | key | A function for computing the group category for each element. | If the key function is not specified or is None, the element itself | is used for grouping. /.../``` I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame. Reply new_to_python Silly Frenchman Posts: 39 Threads: 12 Joined: Feb 2020 Reputation: Feb-08-2020, 02:53 PM (This post was last modified: Feb-08-2020, 02:58 PM by new_to_python.) Thanks. Yes, I read that. Is the key here "consecutive"? Am I correct that in this example, because 'Albert' and ['Alan', 'Adam'] are separated by ['Wes', 'Will'], it is not "consecutive"/following ['Alan', 'Adam']. As a result, it has its own group? (Feb-08-2020, 06:06 AM)Larz60+ Wrote: list needs to be sorted use: ```>>> names = ['Alan', 'Adam', 'Wes', 'Will', 'Albert', 'Steven'] >>> names.sort() >>> for letter, inames in itertools.groupby(names, first_letter): ... print(letter, list(inames)) ... A ['Adam', 'Alan', 'Albert'] S ['Steven'] W ['Wes', 'Will'] >>>```also, you were overwriting names result: Thanks. Is it always better to use a variable name different from the first element of groupby to avoid overwriting it? What is following after "result:"? Reply Larz60+ aetate et sapientia Posts: 10,510 Threads: 396 Joined: Sep 2016 Reputation: Feb-08-2020, 10:50 PM reusing names for different objects is dangerous, but allowed. It's like you had 10 kids all named Pete, some boys and some girls! Reply new_to_python Silly Frenchman Posts: 39 Threads: 12 Joined: Feb 2020 Reputation: Feb-09-2020, 04:14 AM (Feb-08-2020, 10:50 PM)Larz60+ Wrote: reusing names for different objects is dangerous, but allowed. It's like you had 10 kids all named Pete, some boys and some girls! I will keep that in mind. Thanks. So am I correct that because 'Albert' and ['Alan', 'Adam'] are separated by ['Wes', 'Will'], 'Albert' is not consecutive to ['Alan', 'Adam'] and as a result, it forms its own group? Reply Larz60+ aetate et sapientia Posts: 10,510 Threads: 396 Joined: Sep 2016 Reputation: Feb-09-2020, 07:18 AM yes, that's why i added the sort Reply Posts: 1,756 Threads: 8 Joined: Jun 2018 Reputation: Feb-09-2020, 07:52 AM (Feb-09-2020, 04:14 AM)new_to_python Wrote: So am I correct that because 'Albert' and ['Alan', 'Adam'] are separated by ['Wes', 'Will'], 'Albert' is not consecutive to ['Alan', 'Adam'] and as a result, it forms its own group? Python interactive interpreter is excellent tool for observing how stuff 'works': ```>>> s = 'aabbc' >>> itertools.groupby(s) # groupby object, not very helpful >>> list(itertools.groupby(s)) # lets peek inside [('a', ), # groupby object is stream of tuples where: ('b', ), - first element is group name ('c', )] - second element is group itself as grouper object >>> for key, group in itertools.groupby(s): # Let's unpack it into human readable format ... print(f'Group name: {key}, group: {[*group]}') ... Group name: a, group: ['a', 'a'] Group name: b, group: ['b', 'b'] Group name: c, group: ['c'] ```This is basic functionality which might seen not very helpful. But groupby supports key function which enables to do lot of interesting stuff. Some examples below. Filter out numbers from user input/string: ```>>> user_input = ' a34+ *2' >>> for key, group in itertools.groupby(user_input, lambda char: char.isdigit()): # group based on type, key is bool i.e. True or False ... if key: # if group is True ... print(int(''.join(group)) # construct integer from list of strings which are digits ... 34 2 # as list comprehension one-liner: >>> [int(''.join(group)) for key, group in itertools.groupby(user_input, lambda char: char.isdigit()) if key] [34, 2]```Split on many splitters: ```>>> text = 'abcdefghijklm' >>> splitters = ['b','f','j'] # split text on these splitters >>> list(''.join(group) for key, group in itertools.groupby(text, lambda split: split not in splitters) if key) ['a', 'cde', 'ghi', 'klm'] ```Combining with other itertools functions more 'interesting' code can be written. I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame. Reply

 Possibly Related Threads… Thread Author Replies Views Last Post Question on None function in a machine learning algorithm Livingstone1337 1 501 Mar-17-2021, 10:12 PM Last Post: supuflounder Question in python function problem saratha 1 495 Jul-08-2020, 04:56 PM Last Post: jefsummers question about python3 print function jamie_01 5 983 May-25-2020, 09:58 AM Last Post: pyzyx3qwerty Question about list and while function doug2019 6 929 Oct-12-2019, 03:07 AM Last Post: doug2019 Question on Join() function sduvvuri 2 981 Jun-02-2019, 03:55 PM Last Post: perfringo groupby and window function lravikumarvsp 3 1,619 May-13-2018, 06:24 AM Last Post: buran question about list and remove function wmw12344 5 1,774 Mar-30-2018, 11:52 AM Last Post: ljmetzger Basic input() function question rebubula76 2 1,652 Nov-27-2017, 08:12 AM Last Post: buran groups attribute of a groupby object question smw10c 2 2,786 Apr-27-2017, 03:18 PM Last Post: smw10c

Forum Jump:

### User Panel Messages

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