I was recently looking for a language which could help me in learning data science. I stumbled upon this language called Python which has been there since sometime, but is yet to become as popular as C++ or Java. I thought of giving it a try and started learning it online. Since then I have been in love with the simplicity, flexibility and ease of the language. Python has some pretty cool features which automate stuff that had to be done manually in older languages, giving programmers more time to solve the problem at hand rather than doing secondary stuff. In this post I aim to highlight some features of Python which I found really cool and powerful while learning it.
List of Lists
It is very easy to traverse list within lists. The for loop quickly traverses through any complex combination of lists. For those who are new to Python, lists in Python are similar to arrays. You can see in the below code (Line 5-6) how cleanly we can traverse a list containing list as its elements.
n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
for lst in lists:
for numbers in lst:
Displaying Output in a Single Line in Python
The , character after our print statement means that our next print statement keeps printing on the same line.
phrase = "A bird in the hand..."
for i in phrase:
The above code will give the output
A b i r d i n t h e h a n d . . .
in the same line. If we remove the , after the print statement, then the output will be
Enumerate Function in Python
enumerate works by supplying a corresponding index to each element in the list that you pass it. Each time you go through the loop, index will be one greater, and item will be the next item in the sequence. It’s very similar to using a normal for loop with a list, except this gives us an easy way to count how many items we’ve seen so far.
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for x, y in enumerate(choices): # x is the index (0 to 3 here) and y is the item in the list
#x+1 as index starts from 0 which we don't want the user to know.
OUTPUT of the above code will be..
Your choices are:
Zip Function (multiple lists) in Python
zip will create pairs of elements when passed two lists, and will stop at the end of the shorter list. zip can handle three or more lists as well!
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_a, list_b):
I will keep on adding more cool stuff about Python as I get to explore the language. Please give your comments related to any other features of Python which you find cool in the comments section below.
Code courtesy: Codecademy