Avoid using recursion: Recursive functions can slow down your code because they take up a lot of memory. Instead, use iteration.

1. How to get value and index in a loop in Python?

When iterating over a list in Python, if you need both the value and its index, you can use the enumerate function. It returns a tuple containing the index and the value for each element in the list. Here’s an example:

python
lettres = ['a', 'b', 'c', 'd', 'e']

for i, v in enumerate(lettres):
    print(f"lettres[{i}] = {v}")

Output:

css
lettres[0] = a
lettres[1] = b
lettres[2] = c
lettres[3] = d
lettres[4] = e

2. How to eliminate duplicates in a list in Python?

To remove duplicates from a list in Python, you can convert the list to a set. A set automatically eliminates duplicates, and then you can convert it back to a list if needed. Here’s an example:

python
ma_liste = [0, 0, 0, 1, 1, 2, 3, 3, 4]
mon_set = set(ma_liste)
print(mon_set)

# Alternatively, you can use curly braces {} to directly create a set.
set_direct = {0, 0, 0, 1, 1, 2, 3, 3, 4}
print(set_direct)

Output:





{0, 1, 2, 3, 4}

3. How to count the number of occurrences in a list in Python?

If you want to count the occurrences of elements in a list, you can use the Counter class from the collections module. It creates a dictionary with elements as keys and their occurrences as values. Here’s an example:

python
from collections import Counter

ma_liste = ['a', 'a', 'b', 'a', 'c', 'd', 'e']
mon_counter = Counter(ma_liste)

print(mon_counter)
print(mon_counter['a'])  # Access the count for the element 'a'
print(mon_counter.most_common(1))  # Get the most common element with its count

Output:

css
Counter({'a': 3, 'b': 1, 'c': 1, 'd': 1, 'e': 1})
3
[('a', 3)]

4. How to join a list of strings together in Python?

To concatenate a list of strings into a single string, you can use the join() method. It joins the elements of the list with the specified separator (an empty string "" in this case). Here’s an example:

python
ma_liste = ['comment', 'coder', '.com']
result = "".join(ma_liste)
print(result)

Output:





commentcoder.com

5. How to use list comprehensions in Python?

List comprehensions provide a concise and efficient way to create lists in Python. Instead of using a for loop to generate elements and then appending them to a list, you can use a single line of code using list comprehensions. Here’s an example:

python
# Using a for loop
carres = []
for i in range(5):
    carres.append(i * i)
print(carres)

# Using list comprehensions
carres = [i * i for i in range(5)]
print(carres)

Output:

csharp
[0, 1, 4, 9, 16]
[0, 1, 4, 9, 16]

List comprehensions are more Pythonic and improve code readability.

6. How to merge two dictionaries in Python?

To merge two dictionaries in Python, you can use the | operator. This feature is available since Python 3.9. Here’s an example:

python
a = {'x': 1, 'y': 2}
b = {'z': 3}

c = a | b

print(c)

Output:

arduino
{'x': 1, 'y': 2, 'z': 3}

If there are common keys, the values from the second dictionary (b in this case) will override the values from the first dictionary (a).

7. How to remove duplicates and keep the order of a list in Python?

If you have a list with duplicates and you want to remove them while preserving the order, you can use the dict.fromkeys() method. This method removes duplicates and retains the order of the original list. Here’s an example:

python
doublons = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
unique_list = list(dict.fromkeys(doublons))
print(unique_list)

Output:

csharp
[1, 2, 3, 4]

8. How to use else after a for loop?

In Python, you can use the else clause with a for loop. The code within the else block will execute if the loop completes all its iterations without encountering a break statement. Here’s an example:

python
numbers = [2, 4, 6, 8, 1]

for number in numbers:
    if number % 2 == 1:
        print(number)
        break
else:
    print("Pas de nombres impairs")

Output:





1

9. How does list destructuring work in Python?

List destructuring, also known as unpacking, allows you to assign the elements of a list to individual variables in one step. You can use the * symbol to capture the remaining elements as a list. Here’s an example:

python
ma_liste = [1, 2, 3, 4]
un, deux, trois, quatre = ma_liste
print(un, deux, trois, quatre)  # Output: 1 2 3 4

un, deux, *reste = ma_liste
print(un, deux, reste)  # Output: 1 2 [3, 4]

10. How to compare variables with a single condition in Python?

In Python, you can directly compare a variable against two values using the mathematical notation 0 < x < 10. This condition checks if x is greater than 0 and less than 10. It is a more concise way to write conditions that involve multiple comparisons. Here’s an example:

python
x = 5

if 0 < x < 10:
    print("x is between 0 and 10")

11. How to represent large numbers in Python?

Python allows you to represent large numbers in a more readable format by using underscores _. The underscores are ignored by the interpreter and are used only for improved readability. Here’s an example:

python
print(1_000_000)  # Output: 1000000
print(42_000)     # Output: 42000

12. How to get the id of a variable in Python?

You can obtain the unique identifier (id) of a variable in Python using the id() function. The id is a unique integer that represents the memory address where the object is stored. Here’s an example:

python
print(id(1))         # Output: Unique ID of integer 1
print(id("string"))  # Output: Unique ID of the string object
print(id(list()))    # Output: Unique ID of an empty list object

Keep in mind that immutable objects (integers, floats, strings, tuples) have the same id if their values are the same, while mutable objects (lists, sets, dictionaries) have different ids even if their contents are the same.

Recommended: How to Install Bootstrap in React ? SOLVED


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

Avoid using recursion: Recursive functions can slow down your code because they take up a lot of memory. Instead, use iteration.