How To/python/

# -*- coding: utf-8 -*-
 
"""
List Comprehensions
 
_new_list_ = [_return_value_ for _element_ in _list_]
 
_new_list_ = [_return_value_ for _element_ in _list_ if _condition_]
 
_return_value_ - value returned and appended to _new_list_
_list_ - data set
_element_ - element from _list_ list returned by for...in loop
_condition_ - if true append _append_value_, do nothing otherwise
 
"""
 
 
""" 
square numbers
podnies liczby do potegi 2
"""
a = [1,2,3,4,5,6]
b = [i ** 2 for i in a]
print b
#[1, 4, 9, 16, 25, 36]
 
 
"""
square odd numbers only
podnies nieparzyste liczby do potegi 2
"""
a = [1,2,3,4,5,6]
b = [i ** 2 for i in a if i % 2 != 0]
print b
#[1, 9, 25]
 
 
"""
return uppercase strings
wielkie litery
"""
a = ("abc","def","ghj")
b = [z.upper() for z in a]
print b
#['ABC', 'DEF', 'GHJ']
 
 
"""
return uppercase strings from mixed list
wielkie litery z listy zawierającej elementy roznych typow
"""
a = ("abc","def","ghj", 1)
b = [str(z).upper() for z in a]
print b
#['ABC', 'DEF', 'GHJ', '1']
 
 
"""
return uppercase strings from mixed list (2nd verion, without changing type)
wielkie litery z listy zawierającej elementy roznych typow (wersja 2, bez zmiany typów)
"""
def lc_upper(s):
    if isinstance(s, basestring): return s.upper()
    return s
 
a = ("abc","def","ghj", 1)
b = [lc_upper(z) for z in a]
print b
#['ABC', 'DEF', 'GHJ', 1]
 
 
"""
return strings only from mixed list
zwróć tylko stringi z listy zawierającej elementy roznych typow
"""
a = ("abc","def","ghj", 1)
b = [z for z in a if isinstance(z, basestring)]
print b
#['abc', 'def', 'ghj']