Multiple data types in list Python

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

Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.

Lists are created using square brackets:

Create a List:

thislist = ["apple", "banana", "cherry"]
print[thislist]

Try it Yourself »

List Items

List items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered

When we say that lists are ordered, it means that the items have a defined order, and that order will not change.

If you add new items to a list, the new items will be placed at the end of the list.

Note: There are some list methods that will change the order, but in general: the order of the items will not change.

Changeable

The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.

Allow Duplicates

Since lists are indexed, lists can have items with the same value:

Lists allow duplicate values:

thislist = ["apple", "banana", "cherry", "apple", "cherry"]
print[thislist]

Try it Yourself »

List Length

To determine how many items a list has, use the len[] function:

Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]
print[len[thislist]]

Try it Yourself »

List Items - Data Types

List items can be of any data type:

String, int and boolean data types:

list1 = ["apple", "banana", "cherry"] list2 = [1, 5, 7, 9, 3]

list3 = [True, False, False]

Try it Yourself »

A list can contain different data types:

A list with strings, integers and boolean values:

list1 = ["abc", 34, True, 40, "male"]

Try it Yourself »

type[]

From Python's perspective, lists are defined as objects with the data type 'list':

What is the data type of a list?

mylist = ["apple", "banana", "cherry"]
print[type[mylist]]

Try it Yourself »

It is also possible to use the list[] constructor when creating a new list.

Using the list[] constructor to make a List:

thislist = list[["apple", "banana", "cherry"]] # note the double round-brackets
print[thislist]

Try it Yourself »

Python Collections [Arrays]

There are four collection data types in the Python programming language:

  • List is a collection which is ordered and changeable. Allows duplicate members.
  • Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
  • Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
  • Dictionary is a collection which is ordered** and changeable. No duplicate members.

*Set items are unchangeable, but you can remove and/or add items whenever you like.

**As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

When choosing a collection type, it is useful to understand the properties of that type. Choosing the right type for a particular data set could mean retention of meaning, and, it could mean an increase in efficiency or security.


But I want you to also be aware because you will see this that you can mix and match your data types inside of a single list. So even though one of the most common ways that you'll see a list created is having all of the elements to have the same data type. You can change it up a bit and so let's do that here so I can say mixed list here. And the first element can be an integer.

The next element could be a float. The next element could be a string and so on and so forth and so let's see if this is actually working. If I print out mixed_list you'll see that this worked perfectly we have a regular list object where each element is exactly how we represented it right here

We can also even put lists inside of lists. So I could take this user list here paste it all in and if I run that you can see that we now have a list nested inside of another list,

and the cleaner way of doing it as opposed to putting all the elements in is actually storing it in the variable like we have right there. And now I have users here at the very last element and if I run this you can see that it slides the entire list of users right inside at the very end.

and the cool thing is you can run all of the standard list functions inside of it. So if I wanted to do something like this where I could say user list equals mix the list dot pop and that's a function. So we're going to have our per ends at the very end.

And now I can print out our mixed list and our user list. Let's see how this looks. As you can see right here that worked properly.

So we have our regular mixed lists that we printed out here. Then we removed. So we called Pop on this user list the last element and stored it in the user list variable. And you can see that right here

and part of the reason I also wanted to show this to you was every other time that I've called pop it's been on a single element such as a string and that string is what gets returned. However, right here I called pop on an element there was actually a list itself, and as you can see, the list got returned. So whatever the element is whatever that data type as that's what's going to get returned to you and then you can use it however you need it and like you can see the mix list is back to exactly how we created it before we added the users and later on in this section you're going to see when we get into tuples and dictionaries how a very common process is going to be to create a list that stores other collections. So when you run a database query what you're going to get back is a list of other collections so if you called users and you called this user database you wouldn't just get a bunch of string names like that.

We did that in the beginning as an example but a SQL database has much more information so you'd have a name you'd have an email address you'd have a location and all the kind of different elements like that that you'd want to store in your database that can't be kept in a single string. You would actually have another collection that stores all of that. And so that's what I really wanted this guide to focus on was for you to understand that this is a very basic list here and there will be times where you use these types of elements but a very common process is going to be storing other nested collections other nested data structures inside of a list because that makes it possible to iterate over them. Now I want to also point out because this course doesn't just focus on programming but also focuses on industry best practices and I want to point out here on line number five

that what we're doing here is something that could potentially be pretty dangerous. The reason for that is, imagine a scenario where you have this list of elements and you thought that the list only contained numerical data type. So kind of like we have with our IDs, and you start looping over and with each element, you're calling a function on that element. Say you're multiplying it by two or you're adding them all up to get a sum of the values. That would work as long as all of the data types are numeric.

However, if at some point you updated that list, and you added even just one string, it would break your program because if you tried to add the String word "Altuve" to a sum you're going to get an error. So I want to show this to you with the caveat that you need to understand you have to be very careful whenever you're using mixed list data types.

So, whenever you have more than one data type inside of a list it means you're going to have to be very careful with how you treat that list. Typically I try to keep my list as straightforward as possible so I try to keep the exact same data type in there. So that means that if I have a list of other lists then I only want to have a collection of lists that would look something like this. So this would be let's say nested lists and I can have one here. The first element would be this one, the second element would be this list and so on and so forth and they could contain anything that we want. So this could be a list that contains 1 2 3, 2 3 4, 3 4 5. And so the nice thing about this is all of these elements are nested and that means that I'm able to treat them exactly the same way.

What we have here on line 5 is a subtle way of introducing bugs into your program. Now with all that being said, there are some rare times where you'd want to do that. Maybe if you're keeping track of a collection that you don't actually want to iterate over you simply want to have all of the elements in nested inside of one object so you can pass it around and just grab the one-off Elements as you need them and you don't have to really worry about their data types because you know everything that's inside of them.

However, when you're working with things such as large amounts of data or any kind of database query or anything like that then you want to try to keep each one of the elements in your list as uniform as possible so you can treat each one of them the same.

Code

users = ['Kristine', 'Tiffany', 'Jordan', 'Leann'] ids = [1, 2, 3, 4] mixed_list = [42, 10.3, 'Altuve', users] print[mixed_list] user_list = mixed_list.pop[] print[user_list] print[mixed_list] nested_lists = [[123], [234], [345]]

Video liên quan

Chủ Đề