Tutorials  Articles  Notifications  Login  Signup


RK

Rajan Kumar

Founder at HackersFriend April 18, 2020, 4:28 p.m. ⋅ 1975 views

Using advanced Python concepts the easy way ( List comprehensions and Slicing )


Advanced python concepts

 

Python is comparatively easy prgoramming language and its syntax looks very close to normal english. Also, code in python looks very neat and clean as it imposes indentation at block level.

Though, everything is easy in python, there are some 'pythonic' stuffs that are not commonly known to beginners. In this article I'll talk about these advanced python topics.

I'll cover up follwing topics:

  • List comprehension
  • Slicing

 

In upcoming articles I'll talk about

  • Lambda
  • Map
  • Filter
  • Iteration protocol
  • and Generators

 

List comprehension

List comprehensions gives a quick way to iterate over a list and do some operations on each element.

[ SomeFunction(element) for element in GivenList]

This returns a list.

# Python program to organize Odd even elements of an array.

def organize(arr):
  return [element for element in arr if element%2 == 0] + [element for element in arr if element%2 != 0]



arr = [1, 2, 3, 4, 5, 6, 7, 8]
arr = organize(arr)
print (arr)
[2, 4, 6, 8, 1, 3, 5, 7]

 

In this example, organize function first list comprehension will return all the even elements and second list comprehension will return all the odd elements. We are concatinating both of them and returning. This way all the even elements of array is appearing first, them all the odd elements are appearing afterwards.

Slicing

With slicing we can extract a list / sequence / sub sequence out of any given list / sequence. Slicing comes with 3 arguements, start_index, end_index and step_size. Default start_index is 0 and end_index is -1 and step_size is 0. step_size determines how much elements to skip after each selected element. It returns a list.

list[start_index : end_index : step_size]

 

>>> arr = [1, 2, 3, 4, 5, 6, 7, 8]

>>> arr[1:]
[2, 3, 4, 5, 6, 7, 8]

>>> arr[:1]
[1]

>>> arr[1::1]
[2, 3, 4, 5, 6, 7, 8]

>>> arr[1:-1:1]
[2, 3, 4, 5, 6, 7]

>>> arr[1:-1:2]
[2, 4, 6]

>>> arr[1:-1:3]
[2, 5]

 

Step size of -1 means slicing would be from end to start.

 

Header image credits:  Image by Brian Ego from Pixabay 



HackerFriend Logo

Join the community of 1 Lakh+ Developers

Create a free account and get access to tutorials, jobs, hackathons, developer events and neatly written articles.


Create a free account