A2oz

How Do You Convert Data Structures in Python?

Published in Python Data Structures 2 mins read

In Python, you can convert between different data structures using built-in functions and methods.

Common Conversions:

  • List to Set: Use the set() function to convert a list to a set. This eliminates duplicate elements.
      my_list = [1, 2, 2, 3, 4, 4]
      my_set = set(my_list)
      print(my_set)  # Output: {1, 2, 3, 4}
  • Set to List: Use the list() function to convert a set to a list.
      my_set = {1, 2, 3, 4}
      my_list = list(my_set)
      print(my_list)  # Output: [1, 2, 3, 4]
  • List to Tuple: Use the tuple() function to convert a list to a tuple.
      my_list = [1, 2, 3, 4]
      my_tuple = tuple(my_list)
      print(my_tuple)  # Output: (1, 2, 3, 4)
  • Tuple to List: Use the list() function to convert a tuple to a list.
      my_tuple = (1, 2, 3, 4)
      my_list = list(my_tuple)
      print(my_list)  # Output: [1, 2, 3, 4]
  • String to List: Use the list() function to convert a string to a list of characters.
      my_string = "Hello"
      my_list = list(my_string)
      print(my_list)  # Output: ['H', 'e', 'l', 'l', 'o']

More Complex Conversions:

  • Dictionary to List of Tuples: Iterate through the dictionary and create tuples of key-value pairs, then append them to a list.
      my_dict = {'a': 1, 'b': 2, 'c': 3}
      my_list = [(key, value) for key, value in my_dict.items()]
      print(my_list)  # Output: [('a', 1), ('b', 2), ('c', 3)]
  • List of Tuples to Dictionary: Iterate through the list of tuples and create a dictionary with keys and values from the tuples.
      my_list = [('a', 1), ('b', 2), ('c', 3)]
      my_dict = dict(my_list)
      print(my_dict)  # Output: {'a': 1, 'b': 2, 'c': 3}

Practical Insights:

  • Choose the most appropriate data structure based on your needs.
  • Understand the differences between data structures to select the best one for your task.
  • Use built-in functions and methods for efficient conversions.

Related Articles