4 Must-Know Python Data Structures



Original Source Here

List

List is a collection of objects, represented in square brackets.

mylist = [1, 2, "a", True]
  • Lists can be used for storing objects with any data type or a mixture of data types.
  • Lists are mutable. We can add new items to a list or delete the existing ones.
mylist.append(5)
mylist
[1, 2, 'a', True, 5]
mylist += ["b"]
mylist
[1, 2, 'a', True, 5, 'b']
mylist.insert(0, "first")
mylist
['first', 1, 2, 'a', True, 5, 'b']
mylist.remove(2)
mylist
['first', 1, 'a', True, 5, 'b']

The insert method adds the new item at the specified index.

  • Lists are ordered. Thus, we can access the items by their position.
mylist[0]
'first'
mylist[-1]
'b'
mylist[:3]
['first', 1, 'a']
  • We can combine multiple lists using the extend method or “+=” operation.
first = [1, 2, 3]
second = [4, 5, 6]
first += second
print(first)
[1, 2, 3, 4, 5, 6]
first.extend(second)
print(first)
[1, 2, 3, 4, 5, 6, 4, 5, 6]

If you use the append method for this operation, the new list will be added as a new item.

first = [1, 2, 3]
second = [4, 5, 6]
first.append(second)
print(first)
[1, 2, 3, [4, 5, 6]]

AI/ML

Trending AI/ML Article Identified & Digested via Granola by Ramsey Elbasheer; a Machine-Driven RSS Bot

%d bloggers like this: