5 steps to get started with Python data structures

Recommendation: Use NSDT scene editor to quickly build 3D application scenes

Introduction to Python data structures

When learning how to program, regardless of the specific programming language you use for this task, you will find that there are several major topics in your newly chosen discipline into which most of the content you come into contact with can be categorized. Some of these, in general order, are: syntax (the vocabulary of a language); commands (the combination of words into useful ways); flow control (how we direct the order in which commands are executed); algorithms (the things we do to solve a specific problem) Steps... how did this become such a confusing word? Finally, data structures (virtual repositories we use for data manipulation (again...a series of steps) during the execution of an algorithm).

Essentially, if you want to implement a solution to a problem by piecing together a series of commands into the steps of an algorithm, at some point the data will need to be processed and data structures will become essential. Such data structures provide a way to organize and store data efficiently and are essential for creating fast, modular code that can perform useful functions and scale well. Python is a special programming language with its own set of built-in data structures.

This tutorial will focus on the following four basic Python data structures:

  • List - ordered, mutable, allows duplicate elements. Used to store data sequences.
  • Tuple - ordered, immutable, allows duplicate elements. Think of them as immutable lists.
  • Dictionary - Unordered, mutable, map of key-value pairs. Useful for storing data in key-value format.
  • Set - unordered, mutable, containing unique elements. Useful for membership testing and eliminating duplication.

In addition to basic data structures, Python also provides more advanced structures such as heaps, queues, and linked lists, which can further enhance your coding capabilities. These advanced structures build on top of the underlying structures to enable more complex data processing and are often used in specialized scenarios. But you're not limited here; you can also implement your own using all existing structures as a base. However, an understanding of lists, tuples, dictionaries, and sets is still critical, as these are the building blocks of more advanced data structures.

This guide aims to provide a clear and concise understanding of these core constructs. As you begin your Python journey, the following sections will guide you through basic concepts and practical applications. From creating and manipulating lists to leveraging the unique features of collections, this tutorial will give you the skills you need to excel in coding.

Step 1: Working with lists in Python

What is a list in Python?

A list in Python is an ordered, mutable data type that can store a variety of objects, allowing repeated elements. Lists are defined using square brackets, with elements separated by commas.[ ]

For example:

fibs = [0, 1, 1, 2, 3, 5, 8, 13, 21]

Lists are useful for organizing and storing sequences of data.

Create list

Lists can contain different data types such as strings, integers, booleans, etc. For example:

mixed_list = [42, "Hello World!", False, 3.14159]

Operation list

Elements in the list can be accessed, added, changed, and deleted. For example:

# Access 2nd element (indexing begins at '0')
print(mixed_list[1])

# Append element 
mixed_list.append("This is new")

# Change element
mixed_list[0] = 5

# Remove last element
mixed_list.pop(0)

Useful list methods

Some convenient list built-in methods include:

  • sort()- Sort lists in place
  • append()- Add elements to the end of the list
  • insert()- Insert element at index
  • pop()- Delete the element at index
  • remove()- Delete the first occurrence of the value
  • reverse()- Reverse the list in place

Hands-on examples of lists

# Create shopping cart as a list
cart = ["apples", "oranges", "grapes"]

# Sort the list 
cart.sort()

# Add new item 
cart.append("blueberries") 

# Remove first item
cart.pop(0)

print(cart)

Output:

['grapes', 'oranges', 'blueberries']

Step 2: Learn about tuples in Python

What is a tuple?

Tuples are another sequence data type in Python, similar to lists. However, unlike lists, tuples are immutable, meaning their elements cannot be changed once created. They are defined by enclosing the elements in parentheses.( )

# Defining a tuple
my_tuple = (1, 2, 3, 4)

When to use tuples

Tuples are typically used for collections of items that should not be modified. Tuples are faster than lists, which makes them ideal for read-only operations. Some common use cases include:

  • Store constants or configuration data
  • Function return value with multiple components
  • dictionary keys because they are hashable

Access tuple elements

Accessing elements in a tuple is similar to accessing elements of a list. Indexing and slicing work the same way.

# Accessing elements
first_element = my_tuple[0]
sliced_tuple = my_tuple[1:3]

Operations on tuples

Since tuples are immutable, many list operations may or may not apply. However, there are still some things you can do:append()remove()

  • Concatenation: Merge tuples using operators.+
concatenated_tuple = my_tuple + (5, 6)
  • Repeat: Use operators to repeat tuples.*
repeated_tuple = my_tuple * 2
  • Membership: Checks whether an element with a keyword exists in the tuple.in
exists = 1 in my_tuple

tuple method

Tuples have fewer built-in methods compared to lists because they are immutable. Some useful methods include:

  • 计数(): Counts the number of occurrences of a specific element.
count_of_ones = my_tuple.count(1)
  • 索引(): Find the index of the first occurrence of the value.
index_of_first_one = my_tuple.index(1)

Tuple packing and unpacking

Tuple packing and unpacking are convenient functions in Python:

  • Wrapping: Assigning multiple values ​​to a single tuple.
packed_tuple = 1, 2, 3
  • Open: Assign tuple elements to multiple variables.
a, b, c = packed_tuple

Immutable but not strict

Although tuples themselves are immutable, they can contain mutable elements, such as lists.

# Tuple with mutable list
complex_tuple = (1, 2, [3, 4])

Note that while you cannot change the tuple itself, you can modify the mutable elements within it.

Step 3: Master Dictionaries in Python

What is a dictionary in Python?

A dictionary in Python is an unordered, mutable data type used to store unique key-to-value mappings. Dictionaries are written using curly braces and consist of comma-separated key-value pairs.{ }

For example:

student = {"name": "Michael", "age": 22, "city": "Chicago"}

Dictionaries are useful for storing data in a structured manner and accessing values ​​by key.

Create dictionary

Dictionary keys must be immutable objects such as strings, numbers, or tuples. Dictionary values ​​can be any objects.

student = {"name": "Susan", "age": 23}

prices = {"milk": 4.99, "bread": 2.89}

Operation dictionary

Elements can be accessed, added, changed, and deleted via keys.

# Access value by key
print(student["name"])

# Add new key-value 
student["major"] = "computer science"  

# Change value
student["age"] = 25

# Remove key-value
del student["city"]

Useful dictionary methods

Some useful built-in methods include:

  • keys()- return key list
  • values()- Return value list
  • items()- Returns a (key, value) tuple
  • get()- Return the value of the key to avoid key errors
  • pop()- Remove key and return value
  • update()- Add multiple key values

Hands-on examples of dictionaries

scores = {"Francis": 95, "John": 88, "Daniel": 82}

# Add new score
scores["Zoey"] = 97

# Remove John's score
scores.pop("John")  

# Get Daniel's score
print(scores.get("Daniel"))

# Print all student names 
print(scores.keys())

Step 4: Explore collections in Python

What is Set in Python?

A collection in Python is an unordered, mutable collection of unique, immutable objects. Collections are written using curly braces, but unlike dictionaries, they do not have key-value pairs.{ }

For example:

numbers = {1, 2, 3, 4}

Sets are useful for membership testing, duplicate elimination, and mathematical operations.

Create set

A collection can be created from a list by passing the collection to the constructor:set()

my_list = [1, 2, 3, 3, 4]
my_set = set(my_list) # {1, 2, 3, 4}

Collections can contain mixed data types such as strings, booleans, etc.

Operation set

Elements can be added and removed from the collection.

numbers.add(5) 

numbers.remove(1)

Useful collection operations

Some useful set operations include:

  • union()- the returned union of the two groups
  • intersection()- Returns the intersection of sets
  • difference()- Returns the difference between sets
  • symmetric_difference()- Returns the symmetric difference

Hands-on examples of using collections

A = {1, 2, 3, 4}
B = {2, 3, 5, 6}

# Union - combines sets 
print(A | B) 

# Intersection 
print(A & B)

# Difference  
print(A - B)

# Symmetric difference
print(A ^ B)

Step 5: Compare lists, dictionaries, and sets

Feature comparison

Here is a brief comparison of the four Python data structures we mentioned in this tutorial.

structure Order variable Repeating elements Use Cases
list Yes Yes Yes storage sequence
Yuan Yes No Yes Store immutable sequences
dictionary No Yes Key: No
Value: Yes
Store key-value pairs
set up No Yes No Eliminate duplication, member testing

When to use each data structure

Think of this as a soft guide as to which structure to turn to first in a given situation.

  • Use lists for sequence-based ordered data. Useful for stacks/queues.
  • Use tuples for ordered, immutable sequences. Useful when you need a fixed collection of elements that should not change.
  • Use dictionaries for key-value data. Used to store related attributes.
  • Use sets to store unique elements and mathematical operations.

Hands-on examples using all four data structures

Let's take a look at how these structures work together in an example that's a little more complex than a single line.

# Make a list of person names
names = ["John", "Mary", "Bob", "Mary", "Sarah"]

# Make a tuple of additional information (e.g., email)
additional_info = ("[email protected]", "[email protected]", "[email protected]", "[email protected]", "[email protected]")

# Make set to remove duplicates
unique_names = set(names)

# Make dictionary of name-age pairs
persons = {}
for name in unique_names:
  persons[name] = random.randint(20,40)

print(persons)

Output:

{'John': 34, 'Bob': 29, 'Sarah': 25, 'Mary': 21}

This example uses a list to store the ordered sequence, a tuple to store other immutable information, a set to remove duplicates, and a dictionary to store key-value pairs.

go ahead

In this comprehensive tutorial, we take a deep dive into basic data structures in Python, including lists, tuples, dictionaries, and sets. These structures form the building blocks of Python programming, providing a framework for data storage, processing, and manipulation. Understanding these structures is critical to writing efficient and scalable code. From using lists to manipulate sequences, to using key-value pairs in dictionaries to organize data, and ensuring collections are unique, these basic tools provide great flexibility in data processing.

Original link: 5 steps to get started with Python data structures (mvrlink.com)

Guess you like

Origin blog.csdn.net/ygtu2018/article/details/132808121