Home  >  Article  >  Backend Development  >  What are composite data types and data structures in Python?

What are composite data types and data structures in Python?

PHPz
PHPzforward
2023-08-19 16:45:151310browse

What are composite data types and data structures in Python?

In this article, we will explain composite data types and data structures in Python.

So far, variables can only store one value. What if we want to save many related values?

We can simply create different variables for each variable.

But what if we don’t know how many values ​​there will be?

What if we want to use these values ​​in a loop?

Composite data structure is a data type that can store a large number of values.

In Python, there are various types of composite data structures.

  • We will focus mainly on the list.

  • Finally, we’ll take a quick look at Sets, Tuples, and Dictionaries.

List

In Python, a list is an ordered sequence that can hold multiple object types, such as integers, characters, or floating point numbers. In other programming languages, lists are equivalent to arrays.

A list is simply a list of values ​​separated by commas and enclosed in square brackets [].

inputList = [“hello”, “tutorialspoint”, 1, 3.5, “python”]

List operations

There are many operations that can be performed on lists in order to create expressions from them.

1) Use the len() function to get the size of the list

Use len() function Get the length/size of the list (len() method returns the number of items in the object. When the object is a list, the len() function returns the number of items in the list), and create a variable to store it.

Example

# input list
lst = ["Hello", "TutorialsPoint", 78, "Hi", "Everyone"]

# getting list length
listLength = len(lst)

# Printing the size of a list
print("Size of a List = ", listLength)

Output

('Size of a List = ', 5)

Use index to access list elements

The term "indexing" refers to getting an element based on its position in an iterable object.

Indices start from 0. The first element in the sequence is represented by index 0.

Negative indexes start from -1. The last element in the sequence is represented by index -1.

Example

# input list
inputList =[1, 4, 8, 6, 2]

# accessing the list element at index 2 using positive indexing
print("Element at index 2:", inputList[2])

# accessing the last element in list using negative indexing
print("last element of an input list:", inputList[-1])

Output

('Element at index 2:', 8)
('last element of an input list:', 2)

Notice

When we try to use an index that does not exist or is too large, an IndexError

will be thrown

Iterate over the list

Use For Loop

The following program uses a for loop to print all list elements:

# input list
inputList = [10, 20, 30, 40, 50]

print("Input list elements:")
# traversing through all elements of the list using for loop
for element in inputList:
   # printing each element of the list
   print(element)

Output

Input list elements:
10
20
30
40
50

Repeat operator (*) on list items

Python List also includes the * operator, which allows you to create a new list in which elements are repeated a specified number of times.

Example

The following program uses the * operator to repeat a list a given number of times -

# input list
inputList = [5, 6, 7]

# Repeating the input list 2 times using the * operator
print(inputList * 2)

Output

[5, 6, 7, 5, 6, 7]

Here we are multiplying the list of random values ​​twice using * operator so that the output is the given list repeated twice.

Tuples in Python

Tuple is an immutable sequence data type that can contain elements of different data types. A tuple is simply a collection of Python objects separated by commas. Since tuples are static, they are faster than lists.

The syntax of lists and tuples is somewhat different. Lists are represented by square brackets [], while tuples are represented by brackets ().

Tuple slice

We can use tuple slicing. It's similar to how we use strings and lists. Tuple slices are used to get various items. We also use the slicing operator to perform tuple slicing. The slicing operator can be expressed with the following syntax

[start:stop:step]
The Chinese translation of

Example

is:

Example

# Input tuple
givenTuple = ("Welcome", "this", "is", "TutorialsPoint", "Website", 10)

# Slicing with start and stop values(indices)
print('Tuple slicing from index 1 to index 6 :', givenTuple[1:6])

# Slicing with only stop values(indices)
print("Tuple slicing till index 7: ", givenTuple[:7])

Output

Tuple slicing from index 1 to index 6 : ('this', 'is', 'TutorialsPoint', 'Website', 10)
Tuple slicing till index 7: ('Welcome', 'this', 'is', 'TutorialsPoint', 'Website', 10)

Use index to access tuple elements

Like lists, tuples also use indexes to access their elements. The only difference is that tuples are immutable (cannot be changed), while lists are mutable. The Chinese translation of

EXAMPLE

is:

EXAMPLE

# input tuple
inputTuple = (1, 4, 8, 6, 2)

# accessing the tuple element at index 2 using positive indexing
print("Element at index 2:", inputTuple[2])

# accessing the last element in tuple using negative indexing
print("last element of an input tuple:", inputTuple[-1])

Output

('Element at index 2:', 8)
('last element of an input tuple:', 2)

Notice

When we try to use an index that does not exist or is too large, an IndexError

will be thrown

Dictionary in Python

Use the dict.keys() method to get a list of all keys from the dictionary

Apply it to the input dictionary using the keys() function, then convert the result to a list using the list() function (which converts a sequence/iterable to a list) , to print all keys of the dictionary.

The Chinese translation of

Example

is:

Example

# input dictionary
demoDictionary = {10: 'TutorialsPoint', 12: 'Python', 14: 'Codes'}

# Printing the list of keys of a dictionary using the keys() function

# list() methods convert an iterable into a list
print(list(demoDictionary.keys()))

Output

[10, 12, 14]

in conclusion

In this article, we learned about composite data types and data structures, along with some examples of them.

The above is the detailed content of What are composite data types and data structures in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete