|6. Lists in Python
Chapter 6Python Tutorial~1 min read

Lists in Python

Lists — Ordered Collections

List म्हणजे ordered collection जी changeable (mutable) आहे. एकाच variable मध्ये multiple values साठवायला list वापरतात. JavaScript च्या array सारखी आहे.

Marathi Analogy

List म्हणजे shopping list! "दूध, भाजी, साखर, मीठ" — एकामागे एक order मध्ये. list[0] म्हणजे list मधला पहिला item. List मध्ये नंतर items add/remove करता येतात.

List बनवणे आणि access करणे

python
# List बनवणे
fruits = ["Apple", "Mango", "Banana", "Orange"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True, None]  # Mixed types!

# Indexing
print(fruits[0])    # Apple
print(fruits[-1])   # Orange (last item)
print(fruits[1:3])  # ['Mango', 'Banana'] — slicing

# Length
print(len(fruits))  # 4

List Methods — Add/Remove/Change

Common list operations

python
fruits = ["Apple", "Mango", "Banana"]

# ADD
fruits.append("Orange")    # शेवटी add करतो
fruits.insert(1, "Guava")  # index 1 वर insert करतो
print(fruits)  # ['Apple', 'Guava', 'Mango', 'Banana', 'Orange']

# REMOVE
fruits.remove("Mango")  # value by name काढतो
popped = fruits.pop()   # शेवटचा काढतो आणि return करतो
fruits.pop(0)           # index 0 चा काढतो

# CHANGE
fruits[0] = "Strawberry"  # value बदलतो

# OTHER USEFUL METHODS
nums = [3, 1, 4, 1, 5, 9, 2, 6]
nums.sort()       # ascending sort
nums.reverse()    # उलटा करतो
print(nums.count(1))  # 1 किती वेळा आहे? → 2

List Comprehension — One Line मध्ये List

List comprehension

python
# Normal way
squares = []
for i in range(1, 6):
    squares.append(i * i)
print(squares)  # [1, 4, 9, 16, 25]

# List comprehension — same result, एक line!
squares = [i * i for i in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

# With condition — फक्त even numbers
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens)  # [2, 4, 6, 8, 10]

Key Points — लक्षात ठेवा

  • List = [] — ordered, mutable collection
  • .append() — शेवटी add, .insert(i, val) — index वर add
  • .remove(val) — value काढतो, .pop(i) — index काढतो
  • .sort() — ascending, .reverse() — उलटा
  • List comprehension: [expr for item in iterable if condition]
0/12 chapters पूर्ण