obrazky
-

Python Data Structures

array - pole neexistuje v pythone, namiesto toho máme list - zoznam.

  1. List: - definícia: mylist = [“apple”, “banana”, “cherry”]

  2. Tuples - definícia: mytuple = (“apple”, “banana”, “cherry”)

  3. Sets - myset = {“apple”, “banana”, “cherry”}

  4. Dictionaries - thisdict = { “brand”: “Ford”, “model”: “Mustang”, “year”: 1964 }

Summary:

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.

Methods

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the specified value

extend() Add the elements of a list (or any iterable), to the end of the current list

index() Returns the index of the first element with the specified value

insert() Adds an element at the specified position

pop() Removes the element at the specified position

remove() Removes the first item with the specified value

reverse() Reverses the order of the list

sort() Sorts the list

Exercises:

  1. Create a list called numbers containing 5 integers. Add a new number, replace the third number with 100, and print the final list.

  2. Create a list with car names. Sort them alphabetically - ascending and descending.

  3. Create a tuple called dimensions with values (10, 20, 30). Try changing one element. What happens? Print the second element.

  4. Create a set of fruits {‘apple’, ‘banana’, ‘apple’, ‘orange’}. Add ‘grape’ and find the intersection with {‘apple’, ‘grape’}.

  5. Create a dictionary person with keys ’name’, ‘age’, and ‘city’. Print the name, add ‘hobby’ key, and remove the ‘city’ key.

  6. Create a list of your 5 favorite movies and print the first and last one.

  7. Remove duplicates from a list using a set, then convert back to a list.

  8. Increase all student scores by 5 in the dictionary below:

             student = {'name': 'Tom', 'math': 85, 'science': 90, 'english': 78}
    
  9. Given the dictionary below, print the student with the highest score, add a new student, and remove the one with the lowest score.

             scores = {'Alice': 88, 'Bob': 76, 'Charlie': 93}
    

used methods: max(), min(), lists(set()),

-
Copyright © 2008-2025 Miroslava Valíková