Total Pageviews

Saturday, April 18, 2020

LIST IN PYTHON

📘 List in Python 

🎯 What is a List in Python?

A list in Python is a collection of items that is:

  • Ordered (index-based)
  • Changeable (mutable)
  • Allows duplicate values
  • Can store multiple data types

📌 Definition

A list is a data structure in Python used to store multiple values in a single variable.


🧠 Syntax

my_list = [10, 20, 30, "Python", True]

📊 Example List

numbers = [1, 2, 3, 4, 5]

📍 Indexing in List

Element1234
Index0123

⚡ 1. Creating a List

fruits = ["apple", "banana", "mango"]
print(fruits)

Output:

['apple', 'banana', 'mango']

⚡ 2. Accessing Elements

fruits = ["apple", "banana", "mango"]
print(fruits[1])

Output:

banana

⚡ 3. Negative Indexing

fruits = ["apple", "banana", "mango"]
print(fruits[-1])

Output:

mango

⚡ 4. append() → Add Element at End

nums = [1, 2, 3]
nums.append(4)
print(nums)

Output:

[1, 2, 3, 4]

⚡ 5. insert() → Add at Specific Position

nums = [1, 2, 4]
nums.insert(2, 3)
print(nums)

Output:

[1, 2, 3, 4]

⚡ 6. extend() → Add Multiple Items

a = [1, 2]
b = [3, 4]
a.extend(b)
print(a)

Output:

[1, 2, 3, 4]

⚡ 7. remove() → Remove Value

nums = [1, 2, 3, 4]
nums.remove(3)
print(nums)

Output:

[1, 2, 4]

⚡ 8. pop() → Remove by Index

nums = [10, 20, 30]
nums.pop(1)
print(nums)

Output:

[10, 30]

⚡ 9. clear() → Remove All Items

nums = [1, 2, 3]
nums.clear()
print(nums)

Output:

[]

⚡ 10. sort() → Ascending Order

nums = [3, 1, 4, 2]
nums.sort()
print(nums)

Output:

[1, 2, 3, 4]

⚡ 11. sort(reverse=True)

nums = [3, 1, 4, 2]
nums.sort(reverse=True)
print(nums)

Output:

[4, 3, 2, 1]

⚡ 12. reverse()

nums = [1, 2, 3]
nums.reverse()
print(nums)

Output:

[3, 2, 1]

⚡ 13. len() → Length of List

nums = [1, 2, 3, 4]
print(len(nums))

Output:

4

⚡ 14. max()

nums = [10, 50, 20]
print(max(nums))

Output:

50

⚡ 15. min()

nums = [10, 50, 20]
print(min(nums))

Output:

10

⚡ 16. sum()

nums = [1, 2, 3, 4]
print(sum(nums))

Output:

10

⚡ 17. Loop through List

nums = [10, 20, 30]

for i in nums:
print(i)

Output:

10
20
30

⚡ 18. Check Element in List

nums = [1, 2, 3]

print(2 in nums)

Output:

True

⚡ 19. Copy List

a = [1, 2, 3]
b = a.copy()
print(b)

Output:

[1, 2, 3]

⚡ 20. List Slicing

nums = [10, 20, 30, 40, 50]
print(nums[1:4])

Output:

[20, 30, 40]

📌 Summary

✔ List = collection of multiple values
✔ Mutable (can change)
✔ Indexed (0-based)
✔ Supports many built-in methods


🧠 Important Exam Questions

Short Questions

  1. What is a list in Python?
  2. Is list mutable?
  3. What is indexing?
  4. Difference between append and insert?
  5. What is slicing?

Long Questions

  1. Explain list in Python with example.
  2. Write list methods with examples.
  3. Explain append, remove, pop methods.
  4. Write program using list operations.
  5. Explain list slicing with example. 

No comments:

Post a Comment