Understanding List, Dictionary, Tuple & Sets In Python

Neeraj Kushwaha
6 min readJan 27, 2023

--

This is the 5th post in a series of learning the Python programming language.

List

A list in Python is a collection of items that are ordered and changeable. Lists are defined by square brackets [] and the items inside the list are separated by commas. For example, a list of integers could be defined as:

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

Lists can also contain multiple data types, such as:

my_list = [1, "hello", 3.14, True]

There are many useful built-in methods that can be used on lists, such as:

  • append(): adds an item to the end of the list
  • extend(): adds multiple items to the end of the list
  • insert(): adds an item to a specific index in the list
  • remove(): removes an item from the list
  • pop(): removes and returns an item from a specific index in the list
  • clear(): removes all items from the list
  • index(): returns the index of a specific item in the list
  • count(): returns the number of times an item appears in the list
  • sort(): sorts the items in the list in ascending order
  • reverse(): reverses the order of the items in the list

Here are some examples of how these methods can be used:

# create a list of numbers
my_list = [3, 1, 4, 1, 5]

# add an item to the end of the list
my_list.append(6)
print(my_list) # [3, 1, 4, 1, 5, 6]

# add multiple items to the end of the list
my_list.extend([7, 8])
print(my_list) # [3, 1, 4, 1, 5, 6, 7, 8]

# add an item to a specific index in the list
my_list.insert(1, 2)
print(my_list) # [3, 2, 1, 4, 1, 5, 6, 7, 8]

# remove an item from the list
my_list.remove(1)
print(my_list) # [3, 2, 4, 1, 5, 6, 7, 8]

# remove and return an item from a specific index in the list
removed_item = my_list.pop(3)
print(removed_item) # 1
print(my_list) # [3, 2, 4, 5, 6, 7, 8]

# returns the index of a specific item in the list
print(my_list.index(4)) # 2

# returns the number of times an item appears in the list
my_list = [1, 2, 3, 2, 3, 4, 5]
print(my_list.count(2)) # 2

# sorts the items in the list in ascending order
my_list.sort()
print(my_list) # [1, 2, 2, 3, 3, 4, 5]

# reverses the order of the items in the list
my_list.reverse()
print(my_list) # [5, 4, 3, 3, 2, 2, 1]

# remove all items from the list
my_list.clear()
print(my_list) # []

Dictionary

A dictionary in Python is a collection of key-value pairs, where each key is unique. Dictionaries are also known as associative arrays or hash maps in other programming languages. They are enclosed in curly braces {} and the items in a dictionary are separated by commas.

Creating a dictionary

You can create a dictionary in Python using curly braces {} and separating the items with commas. You can also use the built-in dict() function to create an empty dictionary.

Example:

# creating a dictionary using curly braces
my_dict = {"name": "John", "age": 30, "city": "New York"}

# creating an empty dictionary using dict() function
my_dict = dict()

Accessing items in a dictionary: You can access the items in a dictionary by referring to its key.

Example:

my_dict = {"name": "John", "age": 30, "city": "New York"}

# accessing the value of "name" key
print(my_dict["name"]) # Output: "John"

Adding items to a dictionary

You can add items to a dictionary by using the square brackets [] and assigning a value to a new key.

Example:

my_dict = {"name": "John", "age": 30, "city": "New York"}

# adding a new key-value pair
my_dict["email"] = "john@example.com"

Modifying items in a dictionary

You can modify the value of a key by referring to it and assigning a new value.

Example:

my_dict = {"name": "John", "age": 30, "city": "New York"}

# modifying the value of "age" key
my_dict["age"] = 35

Removing items from a dictionary

You can remove items from a dictionary using the del keyword or the pop() method.

Example:

my_dict = {"name": "John", "age": 30, "city": "New York"}

# removing the key-value pair using del keyword
del my_dict["age"]

# removing the key-value pair using pop() method
my_dict.pop("city")

Iterating over a dictionary

You can iterate over a dictionary using a for loop.

Example:

my_dict = {"name": "John", "age": 30, "city": "New York"}

#iterating over dictionary
for key in my_dict:
print(key, my_dict[key])

Tuple

A tuple in Python is an immutable collection of items, enclosed in parentheses () or using the built-in tuple() function. The items in a tuple are separated by commas.

Creating a tuple

You can create a tuple in Python by enclosing the items in parentheses () or using the built-in tuple() function.

Example:

# creating a tuple using parentheses
my_tuple = (1, 2, 3)

# creating a tuple using tuple() function
my_tuple = tuple([1, 2, 3])

Accessing items in a tuple

You can access the items in a tuple by referring to its index. The index starts from 0 and can be accessed using square brackets [].

Example:

my_tuple = (1, 2, 3)

# accessing the first item
print(my_tuple[0]) # Output: 1

Modifying items in a tuple

Since a tuple is immutable, you cannot modify its items. However, you can create a new tuple with the modified items.

Example:

my_tuple = (1, 2, 3)

# creating a new tuple with modified items
new_tuple = (4, ) + my_tuple[1:]
print(new_tuple) # (4, 2, 3)

Adding items to a tuple

You cannot add items to a tuple, since it is immutable. However, you can create a new tuple with the added items.

Example:

my_tuple = (1, 2, 3)

# creating a new tuple with added items
new_tuple = my_tuple + (4, )
print(new_tuple) # (1, 2, 3, 4)

Removing items from a tuple

You cannot remove items from a tuple, since it is immutable. However, you can create a new tuple with the removed items.

Example:

my_tuple = (1, 2, 3)

# creating a new tuple with removed items
new_tuple = my_tuple[:1] + my_tuple[2:]
print(new_tuple) # (1, 3)

Iterating over a tuple

You can iterate over a tuple using a for loop.

Example:

my_tuple = (1, 2, 3)

#iterating over tuple
for item in my_tuple:
print(item)

Sets

A set in Python is an unordered collection of unique items, enclosed in curly braces {} or using the built-in set() function. The items in a set are separated by commas.

Creating a set

You can create a set in Python by enclosing the items in curly braces {} or using the built-in set() function.

Example:

# creating a set using curly braces
my_set = {1, 2, 3}

# creating a set using set() function
my_set = set([1, 2, 3])

Accessing items in a set

You cannot access items in a set by index, since it is unordered. However, you can check if an item is in the set using the in keyword.

Example:

my_set = {1, 2, 3}

# checking if an item is in the set
print(1 in my_set) # Output: True

Adding items to a set

You can add items to a set using the add() method or the |= operator.

Example:

my_set = {1, 2, 3}

# adding an item using add() method
my_set.add(4)

# adding an item using |= operator
my_set |= {5}

Removing items from a set

You can remove items from a set using the remove() method or the -= operator.

Example:

my_set = {1, 2, 3}

# removing an item using remove() method
my_set.remove(2)

# removing an item using -= operator
my_set -= {3}

Iterating over a set

You can iterate over a set using a for loop.

Example:

my_set = {1, 2, 3}

#iterating over set
for item in my_set:
print(item)

Summary

  • Dictionaries are an important data structure in Python and are widely used in various applications. They offer a convenient way to store and retrieve data and are efficient in terms of time complexity.
  • A tuple is a useful data structure in Python when you want to store an immutable collection of items. They can be used to store a collection of items that shouldn’t be modified, like the days of the week or the months of the year. They are also more efficient in terms of time complexity as compared to lists. Additionally, tuple can be used as keys in dictionaries and elements of sets, which lists cannot.
  • Sets are useful in python when you need to store unique items and perform operations like union, intersection, difference, and membership testing. Additionally, sets have a more efficient time complexity for certain operations like adding an item, removing an item, and checking for the existence of an item compared to lists and tuples.

If you like the post, don’t forget to clap. If you’d like to connect, you can find me on LinkedIn.

References:

https://www.python.org/doc/

--

--

Neeraj Kushwaha
Neeraj Kushwaha

Written by Neeraj Kushwaha

https://www.learncsdesign.com “Walking on water and developing software from a specification are easy if both are frozen”

No responses yet