Change language

Built-in data structures in Python

| |

The above topics are divided into four sections below.

  1. Lists: Lists in Python are one of the most versatile collection object types available. The other two types — they are dictionaries and tuples, but they really are more like variants of lists.
    • Python lists do most of the collection data structures found in other languages, and because they are built-in, you don’t have to worry about creating them manually.
    • Lists can be used for any type of object, from numbers and strings to multiple lists.
    • They are accessed in the same way as strings (for example, slicing and concatenating ), so they are easy to use and variable in length, meaning they grow and shrink automatically as you use them.
    • In reality, Python lists — these are C arrays inside the Python interpreter that act like an array of pointers.

    # Python program for illustration
    # Simple list

     
    # List declaration

    L = [ 1 , "a" , "string" , 1 + 2 ]

    print L

     
    # add 6 to the above list < / code>

    L.append ( 6 )

    print L

      
    # pop removes the last item from the list
    L.pop ()

    print L

      

    print L [ 1 ]

    Output:

     [1, ’a’,’ string’, 3] [1, ’a’,’ string’, 3, 6] [1, ’a’,’ string’, 3] a 

    There are various functions that can be performed on lists, such as append (), extend (), reverse (), pop (), etc. To learn more about list methods, click here .

  2.   Dictionary: in python, a dictionary is similar to hash or maps in other languages. It consists of key-value pairs. The value can be accessed by a unique key in the dictionary.
    • Keys are unique and immutable objects.
    • Syntax:
       dictionary = {"key name": value} 

    # Python program for illustration
    # Glossary

     
    # Create a new dictionary

    d = dict () # or d = {}

     
    # Add key-value pairs into the dictionary

    d [ ’xyz’ ] = 123

     d [ ’abc’ ] = 345

     
    # print the entire dictionary

    print d

     
    # print only keys

    print d.keys ()

     
    # print values ​​only

    print d.values ​​()

     
    # iterate over the dictionary

    for i in d:

    print < / code> "% s% d" % (i, d [i])

     
    # another iteration method

    for index, value in enumerate (d):

    print index, value, d [value]

     
    # check if the key exists

    print ’xyz’ in d

     
    # remove key-value pair

    del d [ ’xyz’ ]

     
    # check again

    print "xyz" in d

    Exit:

     {’xyz’: 123,’ abc’: 345} [’xyz’,’ abc’] [123, 345] xyz 123 abc 345 0 xyz 123 1 abc 345 True False 

    () An empty tuple t1 = (0,) A one-item tuple (not an expression) t2 = (0, 1, 2, 3) A four-item tuple t3 = 0, 1, 2, 3 Another four-item tuple (same as prior line, just minus the parenthesis) t3 = (’abc’, (’def’, ’ghi’)) Nested tuples t1 [n], t3 [n] [j] Index t1 [i: j], Slice len (tl) Length

    # Python program for illustration
    # tuple

    tup = ( 1 , " a " , " string " , 1 + 2 )

     print tup

    print tup [ 1 ]

    Output:

     (1, ’a’,’ string’, 3) a 

    A detailed article on tuples in Python

  3. Sets: An unordered collection of unique objects.
    • Set operations such as union (|), intersection (& amp;), difference (-) can be applied to a set.
    • Sets are immutable, i.e. once created, no further data can be added to it
    • () is used to represent the set. Objects enclosed in these brackets will be treated as a set.

    # Python program to demonstrate how it works
    # Install in Python

     
    # Create two sets

    set1 = set ()

    set2 = set ()

     
    # Adding elements to set1

    for i in range ( 1 , 6 ):

      set1.add (i)

      
    # Adding elements to set2

    for i in range ( 3 , 8 ):

    set2.add (i)

     

    print ( "Set1 =" , set1)

    print ( "Set2 =" , set2)

    print ( " " )

    Output:

     (’Set1 =’, set ([ 1, 2, 3, 4, 5])) (’Set2 =’, set ([3, 4, 5, 6, 7])) 

    To learn more about sets in python, read our See the article on sets, Python basics and important topics.

    This article courtesy of Harsh Wardhan Chaudhary (Intern) . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

    Please post comments if you find anything wrong or if you’d like to share more information on the topic discussed above.

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically