{{announcement.body}}
{{announcement.title}}

10 Python Particulars to Know

DZone 's Guide to

10 Python Particulars to Know

If you're just getting started with Python, take a look at ten elements of the Python programming language that are useful to know!

· Web Dev Zone ·
Free Resource

Like many software developers, I have learned my share of software languages over the years. Two years ago, I wrote a post on LinkedIn where I identified 29 software languages I had learned in the 37 years prior; everything from Basic to Ruby to JavaScript and obscure languages like APL and Clipper. As all developers know, in the software engineering field it’s important to keep up with emerging programming languages, so even to this day, I’m learning new ones. Similarly, like many other developers, in my eagerness to quickly learn a new language, I start with similar and familiar code syntax based on programming languages I already know. Using familiar syntax from programming languages you’ve already worked with is initially easier and can jump-start your use of a new language, but there’s a price to pay for that. When doing so, you often avoid learning some of the subtleties and specific features unique to the new language you’re learning, and you may miss some of the differences between the new one and the current languages you know.

At Solution Street, we ask candidates interviewing for developer positions to write some code during the interview. Sometimes we will describe a candidate’s code after an interview as, “He writes Ruby like a Java developer.” This is just another way of saying that, if the candidate was writing in Ruby, he didn’t really make use of some of Ruby’s advantages. I am no different and I often will lazily rely on familiar syntax and control structures when I use a newly-learned language.

“Using familiar syntax from programming languages you’ve already worked with is initially easier and can jump-start your use of a new language, but there’s a price to pay for that.”

Having learned Python a few years ago, I have discovered some new tidbits and tricks that sometimes come in the form of different syntax that could be advantageous to a developer. I want to share some of them with you.

  1. List slicing – List processing is very powerful in Python and although there are many Python packages that enhance list processing, this core capability is very powerful to extract portions of a list. Typically, in other languages you might simply use an iterator to extract what you need, but this concise way is much easier:
Python
 




xxxxxxxxxx
1


1
# list slicing
2
my_list = "Solution Street" # either a string as in this case or a list of elements
3
print(my_list[1:4]) # 1 - 3
4
print(my_list[1:]) # 1 to end
5
print(my_list[:4]) # 0 to 3
6
print(my_list[1:-4]) # 1 to length-4


Output (or run it)

olu
olution Street
Solu
olution St

  1. Operator chaining – Often, when writing code, you come across a conditional saying something like:
Python
 




xxxxxxxxxx
1


 
1
# evaluate the variable between two numbers
2
x = 42
3
print( x >= 0 and x <= 100 ) # returns True


Specifying the condition slightly differently still works:

Python
 




xxxxxxxxxx
1


1
# restated condition
2
x = 42
3
print( 0 <= x and x <= 100 ) # returns True


Python further allows you to take the above statement and simplify it. Some may say this is too terse, but after looking at this more, you may realize the original way is too verbose:

Python
 




xxxxxxxxxx
1


1
# operator chaining
2
x = 42
3
print( 0 <= x <= 100 ) # nice simplified way


Output (or run it)

True

  1. Value swapping – Similar to above, there are more verbose ways of swapping values between variables, but Python’s terse way can be seen as either elegant or difficult to read:
Python
 




xxxxxxxxxx
1
14


1
# value swapping
2
# common way
3
x = 1
4
y = 2
5
temp = y
6
y = x
7
x = temp
8
print(x, y)
9
 
10
# python simplified way
11
a = 1
12
b = 2
13
b, a = a, b
14
print(a, b)


Output (or run it)

(2, 1)
(2, 1)

  1. For else loops – In most languages, we are very familiar with for loops, but Python has this extra added benefit of an else conditional. Often within a loop, you are evaluating a condition and if that condition is true you typically perform some operation and leave the loop. However, you sometimes need to know that the condition was never met and perform some other operation. In most languages, you would do this manually via some additional boolean:
Python
 




xxxxxxxxxx
1
10


1
# standard way
2
found_item = False # init
3
pizza_ingredients = ["cheese","sauce","pineapple","olives","basil"]
4
for i in pizza_ingredients:
5
 if i == "pineapple":
6
   print('This is not a valid pizza.')
7
   found_item = True # set
8
 
9
if(not found_item):
10
 print('This is a real pizza!')


 

With for else loops, it’s more elegant with less code:

Python
 




xxxxxxxxxx
1


 
1
# for else loops
2
pizza_ingredients = ["cheese","sauce","pineapple","olives","basil"]
3
for i in pizza_ingredients:
4
  if i == "pineapple": 
5
    # the else block will not run after using break
6
    print('This is not a valid pizza.')
7
    break
8
else:
9
  print('This is a real pizza!')


Output (or run it)

This is not a valid pizza.

  1. Function argument unpacking – Sometimes in functions/methods of other languages, you need to pass in a set of arguments, but your values are currently stored in an array or key/value pair object (dictionary). Python gives you the ability to pass in a structure and have it unpacked to satisfy the arguments:
Python
 




xxxxxxxxxx
1
11


 
1
# function argument unpacking
2
def do_something(x, y):
3
  print(f'x = {x}')
4
  print(f'y = {y}') 
5
  # then find larger number
6
 
7
tuple_parms = (100, 42)
8
dictionary_parms = {'y': 42, 'x': 100}
9
 
10
do_something(*tuple_parms) # unpack tuple
11
do_something(**dictionary_parms) # unpack dictionary


Output (or run it)

x = 100
y = 42
x = 100
y = 42

  1. Special override called “missing” in dictionaries – How many times have you worked with a dictionary (object/key-value pair) and you needed the key to be initialized? Typically, in the course of your code, you check for null and then initialize it. While this is standard practice, Python has a way to override a special method __missing__ to deal with missing keys when you subclass the built-in dict:
Python
 




xxxxxxxxxx
1
11


1
# using the missing override
2
class MyDict(dict):
3
 def __missing__(self, key):
4
   return_value = []
5
   self[key] = return_value # initialize key
6
   return return_value
7
 
8
m = MyDict()
9
m["foo"].append(1) # no problem with uninitialized key
10
m["foo"].append(2)
11
print(dict(m))


Output (or run it)

{‘foo’: [1, 2]}

  1. Step argument in slice operators – Just a nifty way to walk through a list and skip elements:
Python
 




xxxxxxxxxx
1


1
# The step argument in slice operators.
2
skip_me = "Saorltuhtuirofnf  Satnrkeeelt" # a string is a list too
3
print(skip_me[::2]) # start with 0 position and then skip by 2
4
print(skip_me[::-1]) # go in reverse but don't skip


Output (or run it)

Solution Street
tleeekrntaS fnforiuthutlroaS

  1. Enumerate a list with access to an index – Often, we need to iterate over a list of items but we also need the index. Some languages easily offer this option and some don’t. The simple, additional code method, is to maintain a separate counter while looping but that is extraneous with Python. Python’s enumerate function gives us an iterable where each element is a tuple that contains the index of the item and the original item value:
Python
 




xxxxxxxxxx
1


1
# enumerate with index
2
# wrap an iterable with enumerate and it will yield the item along with its index.
3
a = ['Python', 'Ruby', 'JavaScript', 'Java', 'C#']
4
for index, item in enumerate(a):
5
 # have access to both index and the item
6
 print(index, item)
7
 
8
# full dump of enumerator
9
print(list(enumerate(a)))


Output (or run it)

0 Python
1 Ruby
2 JavaScript
3 Java
4 C#
[(0, ‘Python’), (1, ‘Ruby’), (2, ‘JavaScript’), (3, ‘Java’), (4, ‘C#’)]

  1. List comprehensions – Although it may initially look different, Python allows for a concise and powerful way to create lists. The syntax is brackets containing an expression followed by a ‘for’ clause, then zero or more ‘for’ or ‘if’ clauses. These lists can be conditional or even include operation:
Python
 




xxxxxxxxxx
1
31


1
# List Comprehensions
2
x = []
3
for i in range(5):
4
  x.append(i) # standard way
5
print (x)
6
 
7
x = [i for i in range(5)] # more concise way than above
8
print (x)
9
 
10
# conditional list comprehension
11
# pick vowels from a phrase
12
phrase = "Hello this is a test"
13
vowels = [v for v in phrase if v in 'aeiou']
14
print (vowels)
15
 
16
# operations on list elements
17
prices = [20, 30, 40, 100]
18
 
19
def get_discounted_price(v):
20
  """
21
  5% discount if prices is less or equal to 20,
22
  10% discount for prices > 20
23
  """
24
  if v <= 30:
25
    return v*0.95
26
  else:
27
    return v*0.90
28
 
29
discounted_prices = [get_discounted_price(p) for p in prices]
30
 
31
print(discounted_prices)


Output (or run it)

[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
[‘e’, ‘o’, ‘i’, ‘i’, ‘a’, ‘e’]
[19.0, 28.5, 36.0, 90.0]

  1. Conditions in ternary operator – Frequently, in coding, you find yourself with the need to do a basic if/else condition and in most cases you write the simplistic but multi-line code block like this:
Python
 




xxxxxxxxxx
1


1
x = 42
2
if (x > 100):
3
 print("qualifies")
4
else:
5
 print("not does qualify")


You can be more terse in your statement with Python:

Python
 




xxxxxxxxxx
1


1
# Conditions in Ternary Operator
2
x = 42
3
print("qualifies") if x>100 else print("does not qualify")


Output (or run it)

does not qualify

Topics:
coding, python, python application developers, python coding, software developent, software engineering

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}