Python-02

/

/

/

python/02-collection-data-types

Collection Data-Types

Let's look into the second part of python data-types so you understand how to work with collections of data.

Python-02

/

/

/

python/02-collection-data-types

Collection Data-Types

Let's look into the second part of python data-types so you understand how to work with collections of data.

Lesson Objectives

  • Learn about Collection Data Types:

    • List

    • Tuple

    • Set

    • Dictionary

  • How to get items from collections

  • List Slicing

Are you Ready?

Summary

Intro

We've just covered basic data-types and variables. And now let's go deeper and explore collection data types that can store a lot more data than a single text or numeric value.

Here are the collection types we are going to cover:

  • List

  • Tuple

  • Set

  • Dict

Alright, so you know that we can create variables to store a basic data. But we often need to store a lot more data than a single text or numeric value. Therefore let’s explore collection data types.

List and Tuples

Firstly let’s talk about List and tuples. They are both containers that can hold a lot of data in an ordered list.

Lists are define with square brackets [1,2,3,4,5]
Tuples are defined with parenthesis (1,2,3,4,5)

💡Each item in collection should be separated with a comma and you can put any data inside such as text, numbers, other lists, tuples and so on…

The biggest difference between lists and tuples is that lists are mutable and tuples are immutable. In simple terms, we can make changes to lists, but we can not change tuples.

In general you will use lists for 99% use-cases, so you can add, remove, sort and modify your lists.

And don’t worry much about tuples, they are mostly used when you work with fixed data like coordinates or on a very large data sets because they take less memory and therefore faster. But you won't notice the difference unless you work with many million or billions rows of data. Then it starts to matter.

Let's create an example of lists and tuples and print them:

#🪄 Welcome to Collection DataTypes Introduction

#1️⃣ List/Tuples
list_cat  = ['Walls', 'Floors', 'Roofs', 'Windows','Doors']
tuple_cat = ('Walls', 'Floors', 'Roofs', 'Windows','Doors')

print(list_cat)
print(tuple_cat)

Set

Let's look at the next data-type, which is called Set.

Set is a collection of unique items. It can be used to get rid of duplicates in your tuples or lists.

It’s defined with { } curly braces and then you can put your values inside. This time I will put numbers, but you can also put text if you want to.

#2️⃣ Set - Collection of unique items
set_items = {1,2,3,4,5,3,3,4,'ab', 'ba', 'ab'}
print(set_items)

If you execute the code above you will notice that all duplicates of 3 and ab are gone. That's what sets are used for.

Convert Data

You can also convert your data types.

For example you can have a list of categories and it might contain a few duplicates. If you would want to get rid of duplicates, you could convert your list to as set and then back to list.

Here is code example:

#3️⃣ Convert Types
list_cat        = ['Walls', 'Floors', 'Walls', 'Floors', 'Roofs', 'Windows','Doors']
set_unique_cat  = set(list_cat)
list_unique_cat = list(set_unique_cat)

print(set_unique_cat)
print(list_unique_cat)
Dictionary

The final collection data type is Dictionary. It can be a bit confusing, but it's very useful in Revit API.

Firstly, do not confuse set and dictionaries because they both use curly-braces {}, but have completely different use case.

#4️⃣ Dictionary - Mapped Collection
example_set = {1,2,3,3}
example_dict = {'key':'value',
                'key2' : 'value2'
                }

Dictionary is a mapped collection of data, where each value has a key that represents it.

Think of a real word dictionary.

Let's say you've just heard the word 'Defenestration. You could open up the dictionary, look up this word and get its definition: 'Defenestration is an act of throwing someone out of a window.' (I wonder who made that one up…)

The same is with python dictionaries. You can create a collection where you have a key word that can be used to get the value associated with it.

For example:

#4️⃣ Dictionary 

data_types = {
    "int"     : "A whole number, like 1, 2, or 3.",
    "float"   : "A number that can have a decimal point, like 2.5 or 0.1.",
    "str"     : "Words or letters, like 'hello' or 'apple'.",
    "bool"    : "True/False. Similar to Yes/No parameter in Revit.",
    "list"    : "A group of things you can change, like [1, 2, 'apple'].",
    "tuple"   : "A collection of things you can’t change, like (1, 2, 'apple').",
    "dict"    : "Pairs of things, like {'name': 'John', 'age': 10}.",
    "set"     : "A group of unique things, like {1, 2, 3}. Duplicates ignored.",
    "NoneType": "Means nothing or empty, like an empty box."
}

💡Keys always have to be strings, but values can be any data type you want.

Get data from List / Tuple

While working with lists or any other data types you would often need to get items out of it.

And you can do so by using square brackets after your collection, and specifying the index of the item you want to get. However, keep in mind that in python we always start counting from 0.

So here is an example of how to get items from lists and tuples.

#5️⃣ Get Items from collections
list_cat  = ['Walls', 'Floors', 'Roofs', 'Windows','Doors']
tuple_cat = ('Walls', 'Floors', 'Roofs', 'Windows','Doors')

item_a = list_cat[2]
item_b = tuple_cat[4]
last_item = list_cat[-1]
last_item2 = list_cat[-2]

# out = list_cat[100] # IndexError: list index out of range

Also notice that if you would want to get the last item, you could use negative values starting count with -1. Here is an image to describe it better:

If you would try to get an item outside of the list range, then you would get an error saying IndexError: list index out of range.

Get data from Set

When working with sets, you can not get items by index, because sets are not ordered collection. You could convert set into a list to do so, but not on the sets directly.

For example this would give you a TypeError: 'set' object is not subscriptable.

Subscriptable refers to getting items using square brackets [0]

print(set_items[0]) #TypeError: 'set' object is not subscriptable
Get data from Dict

Also, If you want to get data out of Dictionaries you can not use numeric indexes (dict_data[0]). Dictionaries are not ordered collections, therefore you can not use positions.

Dictionaries are mapped collections.
So, instead of using numeric index, you should use the specified Key value which must be a string (text in quotes). And we can use the key to get its value exactly how you would use word dictionary in real world.

data_types = {
    "int"     : "A whole number, like 1, 2, or 3.",
    "float"   : "A number that can have a decimal point, like 2.5 or 0.1.",
    "str"     : "Words or letters, like 'hello' or 'apple'.",
    "bool"    : "True/False. Similar to Yes/No parameter in Revit.",
    "list"    : "A group of things you can change, like [1, 2, 'apple'].",
    "tuple"   : "A collection of things you can’t change, like (1, 2, 'apple').",
    "dict"    : "Pairs of things, like {'name': 'John', 'age': 10}.",
    "set"     : "A group of unique things, like {1, 2, 3}. Duplicates ignored.",
    "NoneType": "Means nothing or empty, like an empty box."
}

# Get Items from Dict
print(data_types['list'])
print(data_types['tuple'])
print(data_types['set'])
print(data_types['dict'])

Keep in mind that you will get an error message if you try to use a Key that doesn't exist in a dictionary.

And don't worry, errors are totally normal in programming. They are not crashing your computer, they are notifying you that something is not logical to computer. I will show you later how to avoid or handle errors in python. For now just ignore it.

Dicitonary Methods

I also want to go a little ahead of myself, and introduce you to dictionary functionality using methods. There are 3 most important ones:

  • .keys() - Get List of all Keys in a dictionary

  • .values() - Get a list of all Values in a dictionary

  • .items() - Get a list of both Keys and Values as tuples.

Here is a code snippet you could try. And don't worry we will cover all methods later on in more detail.

# Read Dict
print(data_types)
print(data_types.keys())
print(data_types.values())
print(data_types.items())
List Slicing

Lastly, I want to introduce you to list slicing.

List Slicing allows you to get a chunk of data by specifying the start index, end index or both and you can use colon inside square brackets to do that [start : end] .

Here is a syntax example for that:

#6️⃣ List Slicing
list_cat  = ['Walls', 'Floors', 'Roofs', 'Windows','Doors']
print(list_cat[:3])
print(list_cat[3:])
print(list_cat[1:3])

Use this simple sketches to understand what you get.

Outro

Alright, and that’s the collection data types you should know about.

  • list <- You will use lists 80-95% of the time

  • tuples

  • set

  • dict

#1️⃣ List
list_cat  = ['Walls', 'Floors', 'Roofs', 'Windows','Doors']

#2️⃣ Tuple
tuple_cat = ('Walls', 'Floors', 'Roofs', 'Windows','Doors')


#3️⃣ Set - Collection of unique items
set_items = {1,2,3,4,5,3,3,4,'ab', 'ba', 'ab'}


#4️⃣ Dictionary - Mapped Collection
example_dict = {'key':'value',
                'key2' : 'value2'
                }

You might still feel a bit confused why we need each one, so just keep in mind that you need lists 90% of the time, so focus a lot on that. And the others you will occasionally need to use.

HomeWork

Alright, enough watching how I do that, it's time you also get your hands dirty.

Go over the code snippets in this lesson and try it out yourself. Try to experiment and add different data inside and try getting values out of your collections.

But make sure you pay the most attention to lists, as they are the most important collection Data Type you would need.

It’s a simple step, but it’s really useful for you to type it all out and see what happens.

⌨️ Happy Coding!

Questions:

Where would I use Dictionary?

Where would I use Dictionary?

Do I need tuple?

Do I need tuple?

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Discuss the lesson :

P.S. Sometimes this chat might experience connection issues.

Use Discord App for best experience.

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

Unlock Community

The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.

Use coupon code "upgrade" to get 150EUR Discount as a member.

⌨️ Happy Coding!

© 2023-2024 EF Learn Revit API

© 2023-2024 EF Learn Revit API

© 2023-2024 EF Learn Revit API