Python
  • Getting Started
    • Input and Output
    • Variables
    • Data Types
    • Conditional Structures
      • Humidity Level
      • Financial Transactions
      • Fruit-Vending Machine
      • Magic While
      • FizzBuzz
    • Functions
      • Hashtag Generator
  • Data Structures
    • Lists
    • Dictionary
    • Set
    • Interpreter Expressions
  • OOPs
    • Classes and Objects
    • Exception Handling
      • Simple Calculator
  • System Programming
    • File Operations
    • Directory Navigation
    • Process Creation
    • Threads
Powered by GitBook
On this page
  1. Data Structures

Lists

I LOVE DOING THIS :)

A List is a collection of items that are ordered and changeable. Lists are written with square brackets, and the items are separated by commas hence they are Heterogeneous / Dynamic

>>> fruits = ['apple', 'banana', 'orange', 'mango']
>>> print(fruits[0])
apple
>>> print(fruits[-1])
mango

>>> fruits[0] = "peer"
>>> print(fruits)
['peer','banana','orange','mango']

You can also add new items to a list by using the append() method or by inserting them at a specific position with the insert() method

>>> fruits.append('strawberry')
>>> print(fruits)  
['pear', 'banana', 'orange', 'mango', 'strawberry']

>>> fruits.insert(1, 'kiwi')
>>> print(fruits)
['pear', 'kiwi', 'banana', 'orange', 'mango', 'strawberry']

You can remove items from a list by using the remove() method or by deleting them at a specific position with the del statement

>>> fruits.remove('banana')
>>> print(fruits)  
['pear', 'kiwi', 'orange', 'mango', 'strawberry']

>>> del fruits[3]
>>> print(fruits)
['pear', 'kiwi', 'orange', 'strawberry']

If you have an unsorted list [4,3,5,1], you can sort it using the sort method

>>> some_numbers = [4,3,5,1]
>>> some_numbers.sort()
>>> some_numbers
[1, 3, 4, 5]

If you have a list [1, 3, 4, 5] and you need to reverse it, you can call the reverse method

>>> some_numbers = [1, 3, 4, 5]
>>> some_numbers.reverse()
>>> print(some_numbers)
[5, 4, 3, 1]

Similar to the sort method, you can also use the sorted function which also sorts the list. The difference is that it returns the sorted list, while the sort method sorts the list in place. So this function can be used when you want to preserve the original list as well.

>>> some_numbers = [4,3,5,1]
>>> print(sorted(some_numbers))
[1, 3, 4, 5]
>>> print(some_numbers)
[4, 3, 5, 1]
PreviousHashtag GeneratorNextDictionary

Last updated 2 years ago