DEV Community

SCDan0624
SCDan0624

Posted on

Lists, Tuples, and Sets in Python

Intro

Lists, tuples, and sets are 3 built in Python data types to store multiple variables. While they may serve the same function, each built in data type has a few key differences.

Lists

The list data types have the following traits:
1.Lists are written with brackets.
2.The items in a list are ordered.
3.The items in the list can be changed.
4.Duplicate items in a list are allowed.

Create a list

To create a list we use the following syntax:

l = ["Bob", "Rolf", "Anne"]
print(l) # prints ["Bob", "Rolf", "Anne"]
Enter fullscreen mode Exit fullscreen mode

Print a list item

Because list items are ordered we print them using an index. The first item has an index of 0 the next item an index of one and so on:

print(l[0]) # prints "Bob" 
print(l[2]) # prints "Anne" 
Enter fullscreen mode Exit fullscreen mode

Change a list element

To change an element in a list you refer to the index number :

l = ["Bob", "Rolf", "Anne"]
l[0] = "Smith"
print(l) # prints ["Smith", "Rolf", "Anne"]
Enter fullscreen mode Exit fullscreen mode

Add to a list element

To add an element to the end of a list we use the append() method:

l = ["Bob", "Rolf", "Anne"]
l.append("Smithy")
print(l) # ['Bob', 'Rolf', 'Anne', 'Smithy']

Enter fullscreen mode Exit fullscreen mode

Remove a list item

To remove a list item we use the remove() method

l = ["Bob", "Rolf", "Anne"]
l.remove("Rolf")
print(l) # prints ['Bob', 'Anne']

Enter fullscreen mode Exit fullscreen mode

Sets

The set data type has the following traits:
1.Sets are written with curly braces.
2.Sets are unordered.
3.Sets are not indexed.

Create a Set

To create a set we use the following syntax:

s = {"Bob", "Rolf", "Anne"}
print(s) # prints {"Bob", "Rolf", "Anne"}
Enter fullscreen mode Exit fullscreen mode

Add item to a set

To add an item to a set we use the add() method:

s = {"Bob", "Rolf", "Anne"}
s.add("Smith")
print(s) # prints {"Bob", "Rolf", "Anne","Smith"}
Enter fullscreen mode Exit fullscreen mode

Remove item from a set

To remove an item we use the remove() method:

s = {"Bob", "Rolf", "Anne"}
s.remove("Bob")
print(s) # prints {"Rolf", "Anne"}
Enter fullscreen mode Exit fullscreen mode

Tuples

The tuple data type has the following traits:
1.Tuples are written with round brackets.
2.Tuples are ordered.
3.Tuples are not changeable.

Create a tuple

To create a tuple we use the following syntax:

t = ("Bob", "Rolf", "Anne")
print(t) # prints ("Bob", "Rolf", "Anne")
Enter fullscreen mode Exit fullscreen mode

Access tuple items

Similar to lists we access tuple items using the index number:

t = ("Bob", "Rolf", "Anne")
print(t[1]) # prints "Rolf"

Enter fullscreen mode Exit fullscreen mode

Conclusion

Now you know how to work with 3 of the 4 built in python data types. Next week we will go over the fourth data type in python dictionaries.

Top comments (0)