May I drop list bracket from list?

Peter Otten __peter__ at web.de
Thu Apr 23 06:50:30 EDT 2015


subhabrata.banerji at gmail.com wrote:

> On Thursday, April 23, 2015 at 3:57:28 PM UTC+5:30, Peter Otten wrote:
>> 
>> 
>> > Dear Group,
>> > 
>> > I am trying to read a list of files as
>> > list_of_files = glob.glob('C:\Python27\*.*')
>> > Now I am trying to read each one of them,
>> > convert into list of words, and append to a list
>> > as.
>> > 
>> > list1=[]
>> > for file in list_of_files:
>> >       print file
>> >       fread1=open(file,"r").read()
>> >       fword=fread1.split()
>> >       list1.append(fword)
>> > 
>> > Here the list is a list of lists, but I want only one list not
>> > list of lists.
>> > 
>> > I was thinking of stripping it as, str(list1).strip('[]')
>> > 
>> > but in that case it would be converted to string.
>> > 
>> > Is there a way to do it. I am using Python27 on Windows7 Professional.
>> > Apology for an indentation error.
>> > 
>> > If anybody may please suggest.
>> 
>> You have to understand that the append() method always appends a single
>> item to the list, be that a string or a list or whatever. If you want to
>> append words in a list to the list the logical approach is therefore to
>> loop over the words and invoke append for every word
>> 
>> for word in fword:
>>     list1.append(word)
>> 
>> There is also a dedicated extend() method that takes a list (actually an
>> iterable) and appends all items in that list:
>> 
>> list1.extend(fword)
> 
> Thanks Peter. I tried an example,
>>> ll = [['a'], ['b'], ['c']]
>>>> l = [x for y in ll for x in y]
> 
> I would try your one,too.
> 
> Regards,
> Subhabrata Banerjee.

The expression

[x for y in ll for x in y]

is called "list comprehension" and is syntactic sugar for

l = []
for y in ll:
    for x in y:
        l.append(x)

I suggest that you forget about list comprehensions until you are 
comfortable with the traditional approach that uses for loops. Once you have 
understood that the translation into list comprehensions in situations where 
it looks better is mechanical.




More information about the Python-list mailing list