Win a copy of High Performance Python for Data Analytics this week in the Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Jj Roberts
  • Carey Brown
Bartenders:
  • salvin francis
  • Frits Walraven
  • Piet Souris

What are the square brackets around the print line used for?

 
Ranch Hand
Posts: 169
1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I am a Python Newbie.  What are the square brackets surrounding the print line being used for?

 
Marshal
Posts: 3355
492
Android Eclipse IDE TypeScript Redhat MicroProfile Quarkus Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

kevin Abel wrote:What are the square brackets surrounding the print line being used for?


I don't code in Python, but I believe that it is equivalent to:
 
Ranch Hand
Posts: 32
3
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's a list comprehension, which is nice Pythonic (and functional) way of processing the items in a list to produce another list, just as Ron says.  Using a print() command inside the comprehension is a bit of a hack, as usually you would use a comprehension to create a new list.  List comprehensions are very useful, as you can do lots with them in very little code e.g. filter items, transform items etc, and they do not modify the original list.


If you run the original comprehension in your Python shell, you get results like this:


The command has printed each element from the original list, and also returned a list containing three "None" items - the values returned from the print() command each time.  Because print() returns nothing, the comprehension returns a list of nothings:




 
The fastest and most reliable components of any system are those that are not there. Tiny ad:
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic