Python apply to
Manufacturing, Machine Learning, Vision systems and others 

clases

empty

Python Data Structure

python_WPadReadME_august12


../8/13

REFERENCE

https://docs.python.org/3/tutorial/datastructures.html


del statement

Lists

Data Structures

Tuples and Sequences

..///


A tuple consists of a number of values separated by commas, for instance:


>>>

t = 12345, 54321, 'hello!'

t[0]

12345

t

(12345, 54321, 'hello!')

# Tuples may be nested:

u = t, (1, 2, 3, 4, 5)

u

((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))

# Tuples are immutable:

t[0] = 88888

Traceback (most recent call last):

  File "<stdin>", line 1, in <module>

TypeError: 'tuple' object does not support item assignment

# but they can contain mutable objects:

v = ([1, 2, 3], [3, 2, 1])

v

([1, 2, 3], [3, 2, 1])


///


Sets

Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.


Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.


Here is a brief demonstration:


>>>

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}

print(basket)                      # show that duplicates have been removed

{'orange', 'banana', 'pear', 'apple'}

'orange' in basket                 # fast membership testing

True

'crabgrass' in basket

False


# Demonstrate set operations on unique letters from two words


a = set('abracadabra')

b = set('alacazam')

a                                  # unique letters in a

{'a', 'r', 'b', 'c', 'd'}

a - b                              # letters in a but not in b

{'r', 'd', 'b'}

a | b                              # letters in a or b or both

{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}

a & b                              # letters in both a and b

{'a', 'c'}

a ^ b                              # letters in a or b but not both

{'r', 'd', 'b', 'm', 'z', 'l'}

//

Dictionaries

Another useful data type built into Python is the dictionary (see Mapping Types — dict). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


///

python_WPadReadME_august12

REFERENCE

https://www.freecodecamp.org/news/how-to-use-lists-in-python/

 List in Python?

ordered collection of elements enclosed within square brackets []. 

fruits = ["apple", "banana", "cherry"]elements can be anything you want: numbers, words, even other lists! Just like your backpack, you can rearrange, add, remove, or update these elements as needed.

grocery_list,  to keep track of all the items you need to buy. Each item, such as "apples," "bananas," or "milk," is like an element in your list. elements, called items or values, can be of different data types – numbers, strings, booleans, and even other lists (creating nested structures).

Here's what a simple grocery list might look like in Python:

grocery_list = ["apples", "bananas", "milk"]

fruits = ["apple", "banana", "cherry"]

numbers = [

    1,

    2,

    3,

    4,

    5,

]

mixed_list = ["hello", 3.14, True]



How Indices Work. An index is like the label on each jar. It tells us the position of an item in the list. But here's the trick: in Python, we start counting from 0, not 1. So items in a Python list are labeled starting from 0, then onwards with 1, 2, and so on.

How to Access Elements in a ListTo get the candy from a specific jar, you look at the label and pick the right one. Similarly, to get an item from a list, you use its index. Here's how you do it in Python:

# Let's say we have a list of fruits

fruits = ["apple", "banana", "cherry"]

# To access the first fruit (apple), which is at index 0

first_fruit = fruits[0]

print(first_fruit)  # Output: apple

# To access the second fruit (banana), which is at index 1

second_fruit = fruits[1]

print(second_fruit)  # Output: banana

Operations and Methods

How to Modify a List Unlike strings, lists are mutable. This means you can change their content after you create them. Imagine your list is like a recipe book, where you can add, remove, or rearrange ingredients as you please. Here are key methods for modifying lists:

Append an element Adds an element to the end of the list, like adding a new ingredient to the end of your recipe. Here's the syntax: list_name.append(element)

fruits.append("orange")


Insert an element Inserts an element at a specific index, shifting existing elements if necessary, similar to adding a new ingredient at a specific step in your recipe. Here's the syntax: list_name.insert(index, element) And here's a code example:

fruits.insert(1, "grape")

Remove an element Removes the first occurrence of a specific element, just like removing an ingredient you no longer need from your recipe.Here's the syntax: list_name.remove(element) And here's a code example:

fruits.remove("banana")


Pop an element Removes and returns the element at the given index, similar to taking out an ingredient from a specific step in your recipe.Here's the syntax: list_name.pop(index) And here's a code example:

removed_item = fruits.pop(1)


Extend a list Extends the list by appending all elements from an iterable, like adding more ingredients to your recipe from another recipe.Here's the syntax: list_name.extend(iterable)And here's a code example:more_fruits = ["mango", "pineapple"]

fruits.extend(more_fruits)


How to Slice a List

Slicing a list is like cutting a cake into perfectly-sized slices. Just as you choose where to start cutting, where to end, and how thick each slice should be, slicing a list lets you extract specific portions of data from your list.

Imagine you have a delicious cake, fresh out of the oven. You're tasked with cutting it into slices for your guests. Here's how slicing a list relates to cutting a cake:

Start and End Points

Start Index: This is where you begin cutting the cake. If you start at the first layer of the cake, you might begin at the very edge. When choosing a starting index, you can pick any one you like - it doesn't have to be the first one.

End Index: This is where you stop cutting the cake. If you stop at the third layer, you won't cut beyond that point.

Slice Thickness (Step)

Just like you can cut thicker or thinner slices of cake, in slicing a list, you can decide how many elements to include in each slice. Here's the syntax for slicing:

list_name[start_index:end_index:step]

And here's a code example to show you how it works:

# Let's say we have a list of cake layers

cake_layers = ["chocolate", "vanilla", "strawberry", "lemon", "red velvet"]

# Slicing the cake layers

slice_of_cake = cake_layers[1:4:2]

# Explanation: We're slicing 'cake_layers' starting from index 1 (vanilla) up to index 4 (lemon), 

#             and selecting every second element.

# Result: slice_of_cake will be ["vanilla", "lemon"]

Start Index 1 (vanilla): This is where we begin cutting the cake.

End Index 4 (lemon): We stop cutting at this layer, but we don't include lemon.

Step of 2: We skip every other layer between vanilla and lemon.

Result: We end up with a slice containing only vanilla and lemon layers.

By slicing lists, you can extract specific sections of data tailored to your needs, just like cutting cake slices to suit your guests' preferences.