Skip to content

Lists, Tuples and Sets in Python

Python has built-in collection types to store many values in one variable. The three you will use most are:

TypeSyntaxOrderedChangeableDuplicates
List[1, 2, 3]YesYesAllowed
Tuple(1, 2, 3)YesNoAllowed
Set{1, 2, 3}NoAdd/remove onlyNot allowed

Creating a List and Accessing Items

A list can hold values of different types. Items are accessed by index, starting from 0.

names = ["sudheer", "prachi", "bulbul", "vishal", "Mahesh", "Raja", "Paridhi"]
print(len(names))          # 7

list1 = ["sudheer", 12, 52.365, "amit"]
print(list1[2])            # 52.365

Negative indexing

-1 refers to the last item, -2 to the second last, and so on.

print(names[-1])                 # Paridhi
print(names[len(names) - 1])     # same result using len()

Range of indexes (slicing)

print(names[2:5])     # items 2, 3, 4  (5 is not included)
print(names[:4])      # from the beginning up to index 3
print(names[2:])      # from index 2 to the end
print(names[2:-3])    # from index 2 up to the 3rd item from the end

Check if an Item Exists

if "vishal" in names:
    print("Yes, Vishal is present")
else:
    print("Vishal is not present in the list")

Changing List Items

students = ["sudheer", "aayush", "vishal", "kapil", "rajesh", "amit"]

students[2] = "Rani Ahuja"                              # change one item
students[2:5] = ["Rani Ahuja", "Kishore", "Yaminee"]    # change a range of items
print(students)

Adding Items

students.insert(6, "Hema Malini")     # insert at a position
students.append("Tejpal Singh")       # add at the end

more = ["Surabhi", "Poonam"]
students.extend(more)                 # add all items of another list
print(students)

Removing Items

students.remove("Poonam")     # remove by value
students.pop(2)               # remove by index
students.pop()                # remove the last item
print(students)

Unpacking a List

data = [3, "Divyani", 45.60]
roll, name, marks = data
print(roll, name, marks)

List Comprehension

List comprehension builds a new list in one line from a loop, with an optional condition.

numbers = [i for i in range(4)]
print(numbers)                     # [0, 1, 2, 3]

squares = [i * i for i in range(10) if i % 2 == 0]
print(squares)                     # [0, 4, 16, 36, 64]

Tuples

A tuple is like a list, but it cannot be changed after it is created (it is immutable). Use tuples for fixed data such as coordinates, dates or database rows.

codes = (1234, 5678, 9101)
print(codes)

# codes.append(1)    # AttributeError: 'tuple' object has no attribute 'append'

more_codes = (1, 2, 3, 4)
print(codes + more_codes)      # concatenation creates a NEW tuple

# To change a tuple: convert it to a list, change it, convert back
temp = list(codes)
temp.append(3)
codes = tuple(temp)
print(codes)                   # (1234, 5678, 9101, 3)

Sets

A set stores unique values with no fixed order. Duplicates are removed automatically.

numbers = {2, 3, 4, 2}
print(numbers)          # {2, 3, 4} - the duplicate 2 is removed

for item in {1, 2, 3, 4}:
    print(item)

empty_set = set()       # {} creates an empty dictionary, not a set

Set operations

s1 = {1, 2, 9, 8}
s2 = {3, 5, 7}
print(s1.union(s2))             # all items from both sets
s1.update(s2)                   # add the items of s2 into s1

cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Seoul", "Kabul", "Delhi"}
print(cities.difference(cities2))     # items only in cities: Tokyo, Madrid, Berlin
print(cities.intersection(cities2))   # items in both: Delhi