List comprehensions

Python टूलबॉक्स

Hugo Bowne-Anderson

Data Scientist at DataCamp

for लूप से लिस्ट भरें

nums = [12, 8, 21, 3, 16]

new_nums = []
for num in nums: new_nums.append(num + 1)
print(new_nums)
[13, 9, 22, 4, 17]
Python टूलबॉक्स

एक list comprehension

nums = [12, 8, 21, 3, 16]
new_nums = [num + 1 for num in nums]

print(new_nums)
[13, 9, 22, 4, 17]
Python टूलबॉक्स

For लूप और list comprehension का सिंटैक्स

new_nums = [num + 1 for num in nums]
for num in nums:
    new_nums.append(num + 1)

print(new_nums)
[13, 9, 22, 4, 17]
Python टूलबॉक्स

range() के साथ list comprehension

result = [num for num in range(11)]

print(result)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Python टूलबॉक्स

List comprehensions

  • लिस्ट बनाने वाले for लूप को एक लाइन में समेटें
  • घटक
    • Iterable
    • Iterator वैरिएबल (iterable के सदस्य दर्शाए)
    • आउटपुट एक्सप्रेशन
Python टूलबॉक्स

Nested लूप्स (1)

pairs_1 = []

for num1 in range(0, 2): for num2 in range(6, 8): pairs_1.append((num1, num2))
print(pairs_1)
[(0, 6), (0, 7), (1, 6), (1, 7)]
  • इसे list comprehension से कैसे करें?
Python टूलबॉक्स

Nested लूप्स (2)

pairs_2 = [(num1, num2) for num1 in range(0, 2) for num2 in range(6, 8)]

print(pairs_2)
[(0, 6), (0, 7), (1, 6), (1, 7)]
  • समझौता: पठनीयता
Python टूलबॉक्स

अभ्यास करते हैं!

Python टूलबॉक्स

Preparing Video For Download...