0% found this document useful (0 votes)
5 views9 pages

Python

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views9 pages

Python

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Lists in python

We can store all types of items (including another list) in a list. A


list may contain mixed type of items, this is possible because a
list mainly stores references at contiguous locations and actual
items maybe stored at different locations.
 List can contain duplicate items.
 List in Python are Mutable. Hence, we can modify,
replace or delete the items.
 List are ordered. It maintain the order of elements based
on how they are added.
 Accessing items in List can be done directly using their
position (index), starting from 0.

Ex : a = [10, 20, "GfG", 40, True]


Note: Lists Store References, Not Values

Creating a List
Here are some common methods to create a list:
Using Square Brackets
a = [1, 2, 3, 4, 5]

Using list() Constructor


We can also create a list by passing an iterable (like a string, tuple or
another list) to list() function.

# From a tuple
a = list((1, 2, 3, 'apple', 4.5))

print(a)

Creating List with Repeated Elements


We can create a list with repeated elements using the
multiplication operator.
# Create a list [2, 2, 2, 2, 2]
a = [2] * 5

Accessing List Elements


Elements in a list can be accessed using indexing. Python
indexes start at 0, so a[0] will access the first element,
while negative indexing allows us to access elements from
the end of the list. Like index -1 represents the last elements
of list.

Adding Elements into List


We can add elements to a list using the following methods:
 append(): Adds an element at the end of the list.
 extend(): Adds multiple elements to the end of the
list.
 insert(): Adds an element at a specific position.

Updating Elements into List


We can change the value of an element by accessing it using
its index.
a = [10, 20, 30, 40, 50]
# Change the second element
a[1] = 25
print(a)

Removing Elements from List


We can remove elements from a list using:
 remove(): Removes the first occurrence of an element.
 pop(): Removes the element at a specific index or the last element
 del statement: Deletes an element at a specified index.
Iterating Over Lists
We can iterate the Lists easily by using a for loop or other
iteration methods. Iterating over lists is useful when we want
to do some operation on each item or access specific items
based on certain conditions. Let's take an example to iterate
over the list using for loop.
a = ['apple', 'banana', 'cherry']
# Iterating over the list
for item in a:
print(item)

Nested Lists in Python


A nested list is a list within another list, which is useful for
representing matrices or tables. We can access nested
elements by chaining indexes.

Get a list as input from user in Python

Get list as input Using split() Method


The input() function can be combined with split() to accept
multiple elements in a single line and store them in a list.
The split() method separates input based on spaces and
returns a list.

user_input = input("Enter elements separated by space: ").split()

print("List:", user_input)

1 2 3 4 5
List: ['1', '2', '3', '4', '5']
Get list as input Using map()
If numeric inputs are needed we can use map() to convert them
to integers. Wrap map() in list() to store the result as a list

# Get user input, split it, and convert to integers

user_input = list(map(int, input("Enter numbers separated by space: ").split()))

print("List:", user_input)

Using List Comprehension for Concise Input


List comprehension provides a compact way to create a list
from user input. Combines a loop and input() into a single line
for it be concise and quick.
n = int(input("Enter the number of elements: "))

# Use list comprehension to get inputs

a = [input(f"Enter element {i+1}: ") for i in range(n)]

print("List:", a)

Explanation:
 The outer split(";") separates sublists.
 The inner split(",") creates elements in each sublist.

List Slicing Examples


Let’s see how to use list slicing in Python with the examples below.
Get all the items from a list
To retrieve all items from a list, we can use slicing without specifying any
parameters.

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Get all elements in the list


print(a[::])

print(a[:])

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Get elements from index 1 to 4 (excluded)

print(a[1:4])

Output
[2, 3, 4]

Python List Slicing Syntax:


list_name[start : end : step]
 start (optional): Index to begin the slice (inclusive).
Defaults to 0 if omitted.
 end (optional): Index to end the slice (exclusive).
Defaults to the length of list if omitted.
 step (optional): Step size, specifying the interval
between elements. Defaults to 1 if omitted

Dictionaries

Dictionary
Dictionaries are used to store data values in key:value pairs.

A dictionary is a collection which is ordered*, changeable and do not allow


duplicates.
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Dictionaries are written with curly brackets, and have keys and values:
When we say that dictionaries are ordered, it means that the items have a
defined order, and that order will not change.

Changeable
Duplicates Not Allowed
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}

thisdict = dict(name = "John", age = 36, country = "Norway")


print(thisdict)

Accessing Items
You can access the items of a dictionary by referring to its key name, inside
square brackets:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]

x = thisdict.get("model")

Get Keys
The keys() method will return a list of all the keys in the dictionary.

x = thisdict.keys()
Get Values
The values() method will return a list of all the values in the dictionary.

x = thisdict.values()

Change Values
You can change the value of a specific item by referring to its key name:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018

Update Dictionary
The update() method will update the dictionary with the items from the
given argument.

The argument must be a dictionary, or an iterable object with key:value pairs.

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"year": 2020})

Adding Items
Adding an item to the dictionary is done by using a new index key and
assigning a value to it:

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)

Update Dictionary
The update() method will update the dictionary with the items from a given
argument. If the item does not exist, the item will be added.

The argument must be a dictionary, or an iterable object with key:value pairs.

thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.update({"color": "red"})

Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.

Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair
keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist: insert the

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary

You might also like