5 Python Tricks in one line. Beginner vs Professional
Tags: programming, python, tutorial, beginners
Published: 2021-11-07 09:59:26

Photo by <a href="https://unsplash.com/@altumcode?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">AltumCode</a> on <a href="https://unsplash.com/s/photos/professions-programming?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
  

Python is famous for its simplicity and ease of use. This is achieved, among other things, due to the compactness of the code. At the same time, such conciseness may hide complex program logic. In this article, we will look at 5 examples of "syntactic sugar" for processing sequences, when the built-in constructs of the programming language allow you to write less and easier.

Recall that a sequence is called an iterative data structure or simply an array of elements. In Python, sequences such as list (list), string (str), tuple (tuple), dictionary (dict) or set (set) are most often used.

##CREATING LISTS IN ONE LINE USING LIST COMPREHENSION

Suppose the task is to create a list whose elements are squares of integers. A beginner in programming will do this way:

```python
squares = []
for x in range(10):
    squares.append(x**2)
```

As a result:

```python
result
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

```

Note that range is a sequence of numbers from 0 to 10 (not inclusive), and "**" is the exponentiation operator. Now let's do the same as professional Python developers - the List comprehension construct:

```python
squares = [x**2 for x in range(10)]
```
The result is the same and the code has become more efficient

```python
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
```
List comprehension can be used for complex (nested) loops. For example, let's create pairs of elements from two lists the way a beginner will do it:

```python

first = ['a1', 'a2']; second = ['b1', 'b2']
result = []
for i in first:
    for j in second :
        pair = (i, j)
        result.append(pair)

```
And now a real Python developer with a good level

```python

result = [(i,j) for i in first for j in second]

```

That's how with List comprehension you can shorten the process of creating a list from 5 lines to 1. Any programmer will see in your code the hand of a real competent Python developer

##CREATING DICTIONARIES USING DICT COMPREHENSION

You need to create a dictionary whose value corresponds to the square of the key. The beginner's method requires creating an empty dictionary and a loop with an element-by-element display of the key and value on the next line:

```python

result = {}
for x in range(10):
   result[x] = x**2

```

and result...

```python
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}

```
Yes, we have completed the task. We are programmers. But a real Python professional will only laugh at you.

He will show you the magic

```python
result = {x: x**2 for x in range(10)}

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
```
Note that after x there is a colon separating the key and its value. Similar to a List comprehension, Dict comprehension can be used for nested loops. I hope you noticed that the brackets in the List and Dict comprehensions are different.

##REMOVING DUPLICATES FROM THE LIST

There are duplicate items in the list, and you only need unique values. What will a beginner do? He will definitely create a new list, and in the loop, he will arrange a check for the compliance of the element with the new list. has O(N²) time complexity.:

```python 

fruits = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
new = []
for fruit in fruits:
    if fruit not in new:
        new.append(fruit)

```
and he will get his result

```python
['banana', 'apple', 'pear', 'orange']
```

As you can see, apple and orange are no longer repeated. In the 5th line, our newcomer checks whether an item is in the new list: if there is, then adds, otherwise ignores. Our professional, who knows about sets, will surprise us again with a 1-line solution has O(N) time complexity

```python
# List instead of set
fruits = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']

# Actually make `new` a list
new = list(set(fruits))
['banana', 'apple', 'pear', 'orange']
```
A set is a data structure in which each element is unique. So when you need to exclude duplicate data, use sets

Thanks [kbauer](https://dev.to/kbauer), [ruudvanderham](https://dev.to/ruudvanderham), [jackm767](https://dev.to/jackm767) for useful additions to the article. You can read more information about this item in the comments

### IMPORTANT NOTICE!

The set does not contain duplicate elements;

The elements of the set are immutable (they cannot be changed), but the set itself is changeable, and it can be changed;

Since the elements are not indexed, the sets do not support any slicing and indexing operations.

##UNPACKING THE ITEMS FROM THE LIST

To pull an element out of the sequence, you want to use the index of the element, right? In some cases, this is correct, but Python allows you to assign each element its own variable.
```python
x, y = (15, 5)

x
15

y
5

fruit, num, date = ['apple', 5,(2021, 11, 7)]

date
(2021, 11, 7)
```


##LISTS SLICING IN PYTHON

In the previous example, we unpacked each item from the list. And what if you need to extract under the list? For example, there is a sequence of 5 elements, you need to take only 3 of them. This is also provided in Python:

```python
x = [1, 2, 3, 4, 5]
result = x[:3]

result
[1, 2, 3]
```

A more detailed syntax looks like this:

```python
sequence[start:stop:step]
```

You can omit START if you want to cut from the zero elements, END if you want to cut to the end, and STEP if your default step is 1

For example:

```python

x = [10, 5, 13, 4, 12, 43, 7, 8]
result = x[1:6:2]
result
[5, 4, 43]
```

Now, knowing the syntactic sugar in Python and how to use it effectively, you can safely be called a competent Python developer

>###Put on Heart if you liked it and you learned something new!
###You can also follow [ME](https://dev.to/vadimkolobanov) to receive notifications about new interesting articles.

#### FAQ

**I am a beginner, how should I learn Python?**

Look into the following series:

[Learning Python](https://dev.to/vadimkolobanov/series/15329)
[Step by Step to Junior](https://dev.to/vadimkolobanov/series/15349)
[Ideas](https://dev.to/vadimkolobanov/series/15331)

**Would you mentor me?**

Of course I am ready to participate in the training. The big difficulty is that English is not my native language and it will be possible to communicate through a translator

**Would you like to collaborate on our organization?**

If you have interesting ideas, we will be happy to invite your writing from our organization. Write in private messages or in social networks below

**If you have interesting projects and you need a backend developer, then you can contact me by mail or in discord for cooperation**

**Connect to me on**

[Write me on Face....oh...Meta](https://www.facebook.com/neo.skarynsky)

[My Twitter](https://twitter.com/decodesperato)	

Discord: vadimkolobanov#5875