List

What is a List?

A list is a Python data structure used to store multiple values in one variable. Lists:

  • Are ordered

  • Are changeable

  • Can hold different data types (e.g., strings, numbers)

  • Use square brackets.[]


Create List

name = ["KT", "Baz", "Sashi", "Samu"]
  • You created a list of strings.

  • name[0] → "KT", name[1] → "Baz", and so on.


print(name)              # Shows the whole list
print(type(name))        # Tells you it's a <class 'list'>
print(len(name))         # Counts the number of items (4)

Accessing List Items

print(name[0])           # First item: "KT"
print(name[1])           # Second item: "Baz"

Slicing Lists

print(name[1:3])         # Items from index 1 to 2 → ["Baz", "Sashi"]
print(name[1:])          # From index 1 to end → ["Baz", "Sashi", "Samu"]
print(name[:3])          # From start to index 2 → ["KT", "Baz", "Sashi"]
print(name[-1])          # Last item → "Samu"

Slicing is powerful when you want part of a list.


Adding an Item

name.append("Venu")
  • Adds "Venu" to the end of the list.

  • Now the list is:["KT", "Baz", "Sashi", "Samu", "Venu"]


Removing an Item

name.pop(0)
  • Removes the first item (index 0), which is "KT".

  • Now the list becomes:["Baz", "Sashi", "Samu", "Venu"]


Why Use Lists?

  • To store and manage multiple values

  • To loop over elements and process them

  • To dynamically add, update, or remove items

  • Useful in real-world tasks like to-do lists, cart items, student records, etc.

#!/bin/python3

#List - Have brackets []
name = ["KT","Baz","Sashi","Samu"]
print(name)
print(type(name))
print(len(name))

print(name[0])
print(name[1])
print(name[1:3])
print(name[1:])
print(name[:3])
print(name[-1])


name.append("Venu")
print(name)

 
name.pop(0)
print(name)

Last updated