0% found this document useful (0 votes)
175 views

Python Lists: Contents

This document discusses Python lists. It begins with an introduction to lists and examples of list creation. It then covers various list methods for accessing, modifying, and iterating through list elements. These methods include accessing items, changing values, removing items, checking for existence, getting length, adding items, joining lists, copying lists, reversing, sorting, finding indexes and counts. It also discusses using max, min, and list comprehensions to filter and transform lists in a concise manner using conditional logic.

Uploaded by

manojkumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
175 views

Python Lists: Contents

This document discusses Python lists. It begins with an introduction to lists and examples of list creation. It then covers various list methods for accessing, modifying, and iterating through list elements. These methods include accessing items, changing values, removing items, checking for existence, getting length, adding items, joining lists, copying lists, reversing, sorting, finding indexes and counts. It also discusses using max, min, and list comprehensions to filter and transform lists in a concise manner using conditional logic.

Uploaded by

manojkumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Python Lists

Contents:
1.Introduction
1.1)Python datatypes
1.2)List creation

2.List Methods
2.1)Access Items
2.2)Change Item Value
2.3)Remove Item
2.4)Check if Item Exists
2.5)List Length
2.6)Add Items
2.7)Join Two Lists
2.8)Copy a list
2.9)Reversing a list
2.10)Sorting a list
2.11)Index of a element in list
2.12)Counting number of occurances of a element in list
2.13)Max and min elements in a list

3.List comprehensions
3.1)List Comprehensions with Conditionals
3.2)Nested List Comprehensions
1.Introduction
Data types are the classification or categorization of data items. It represents the kind of
value that tells what operations can be performed on a particular data.
Lists are one of the datatype of python.

They are just like the arrays, declared in other languages. A single list may contain
DataTypes like Integers, Strings, as well as Objects. The elements in a list are separated by
comma , .Lists can be modified.Each element in the list has its definite place in the list,
which allows duplicating of elements in the list.
In Python lists are written with square brackets [ ] and we have forward indexing and
backward indexing.
Example as fallows:
#List with no elements :
list1 = [ ]
print(list1)

#list with single element :


list2 = ["Python"]
print(list2)
Output:: ["Python"]

# list with multiple elements of different data types


list3 = ["Python", 15, 10.5]
print(list3)
Output:: ["Python", 15, 10.5]

#User input list


lst = []
n = int(input("Enter number of elements"))
for i in range(0, n):
elements = int(input())
lst.append(elements)
print(lst)
Input::4
Python
15
10.5
4
Output::["Python", 15, 10.5,4]

# With handling exception


try:
list = []
while True:
list.append(int(input()))
# if input is not-integer, just print the list
except:
print(list)

# taking multiple inputs at a time


# and type casting using list() function
x = list(map(int, input("Enter a multiple value: ").split()))
print("List of elements: ", x)

Input::["Python", 15, 10.5,4]


Output::["Python", 15, 10.5,4]
2.List Mehods

Access Items:
Positive indexing:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Output::banana

Negative indexing:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Output:: cherry

Range of Indexes(Slicing):
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon",
"mango"]
print(thislist[2:5])

The search will start at index 2 (included) and end at index 5


(not included)
Output:: ['cherry', 'orange', 'kiwi']
This example returns the items from "cherry" and to the end:
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:])
Output:: ['cherry', 'orange', 'kiwi', 'melon', 'mango']

This example returns the items from index -4 (included) to index -1 (excluded)
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[-4:-1])
Output:: ['orange', 'kiwi', 'melon']

Change Item Value:


Change the second item:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
Output:: ['apple', 'blackcurrant', 'cherry']

Remove Item:
The remove() method removes the specified item:
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
Output:: ['apple', 'cherry']

The pop() method removes the specified index, (or the last item if index is not specified):
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
Output:: ['apple', 'banana']

The del keyword removes the specified index:


thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
Output:: ['banana', 'cherry']

The del keyword can also delete the list completely:


thislist = ["apple", "banana", "cherry"]
del thislist

#No Output

The clear() method empties the list:


thislist = ["apple", "banana", "cherry"]
thislist.clear()
print(thislist)
Output:: []

Check if Item Exists:


To determine if a specified item is present in a list use the in keyword:
Check if "apple" is present in the list:
thislist = ["apple", "banana", "cherry"]
if "apple" in thislist:
print("Yes, 'apple' is in the fruits list")
Output:: Yes, 'apple' is in the fruits list

List Length:
To determine how many items a list has, use the len() function:
Print the number of items in the list:
thislist = ["apple", "banana", "cherry"]
print(len(thislist))
Output:: 3

Add Items:
Using the append() method to append an item:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Output:: ['apple', 'banana', 'cherry', 'orange']

To add an item at the specified index, use the insert() method:


Insert an item as the second position:
thislist = ["apple", "banana", "cherry"]
thislist.insert(1, "orange")
print(thislist)
Output:: ['apple', 'orange', 'banana', 'cherry']

Join Two Lists:


There are several ways to join, or concatenate, two or more lists in Python.
One of the easiest ways are by using the + operator.
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list3 = list1 + list2
print(list3)
Output:: ['a', 'b', 'c', 1, 2, 3]

Append list2 into list1:


list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
for x in list2:
list1.append(x)
print(list1)
Output:: ['a', 'b', 'c', 1, 2, 3]

We can use the extend() method to add list2 at the end of list1:
list1 = ["a", "b" , "c"]
list2 = [1, 2, 3]
list1.extend(list2)
print(list1)
Output:: ['a', 'b', 'c', 1, 2, 3]

Copy a list:
You cannot copy a list simply by typing list2 = list1, because: list2 will only be a reference
to list1, and changes made in list1 will automatically also be made in list2.
There are ways to make a copy, one way is to use the built-in List method copy().
Make a copy of a list with the copy() method:
thislist = ["apple", "banana", "cherry"]
mylist = thislist.copy()
print(mylist)
Output:: ['apple', 'banana', 'cherry']
Make a copy of a list with the list() method:
thislist = ["apple", "banana", "cherry"]
mylist = list(thislist)
print(mylist)
Output:: ['apple', 'banana', 'cherry']

Reversing a list:
Reverse the order of the fruit list using reverse():
fruits = ['apple', 'banana', 'cherry']
fruits.reverse()
print(fruits)
Output:: ['cherry', 'banana', 'apple']

Sorting a list:
The sort() method sorts the list ascending by default.
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
print(cars)
Output:: ['BMW', 'Ford', 'Volvo']

Sort the list descending:


cars = ['Ford', 'BMW', 'Volvo']
cars.sort(reverse=True)
print(cars)
Output:: ['Volvo', 'Ford', 'BMW']

Index of a element in list:


The index() method returns the position at the first occurrence of the specified value.
fruits = ['apple', 'banana', 'cherry']
x = fruits.index("cherry")
print(x)
Output:: 2

Counting number of occurances of a element in list:


The count() method returns the number of elements with the specified value.
fruits = ['cherry', 'banana', 'cherry']
x = fruits.count("cherry")
print(x)
Output:: 2

Max and min elements in a list:


max() and min() methods used to know the maximum and minimum elements in a list.
List = [1, 2, 3]
print(max(List))
print(min(List))
Output:: 3
1

3.List comprehensions

List Comprehensions with Conditionals:


You can adjust the control flow of your comprehensions with the help of conditionals.
list = [x for x in range(10) if x%2==0]
print(list)
Output:: [0, 2, 4, 6, 8]

Note that you can rewrite the above code with a Python for loop easily as fallows,
list = []
for x in range(10)
if x % 2 == 0:
list.append(x)
print(list)
Output:: [0, 2, 4, 6, 8]

Multiple If Conditions:
Now that you have understood how you can add conditions, it's time to convert the
following for loop to a list comprehension with conditionals.
list= []
for x in range(100):
if x%2 == 0 :
if x%6 == 0:
list.append(x)
print(list)
Output:: [0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96]

Now this can be converted into list comprehension as fallows,


list = [x for x in range(100) if x % 2 == 0 if x % 6 == 0]
print(list)
Output:: [0, 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, 72, 78, 84, 90, 96]

If-Else Conditions:
Of course, it's much more common to work with conditionals that involve more than one
condition. That's right, you'll more often see if in combination with elif and else. Now, how
do you deal with that if you plan to rewrite your code?
Take a look at the following example of such a more complex conditional in a for loop:
list= [x+1 if x >= 20 else x+5 for x in range(20)]
print(list)
Output:: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24]

Now look at the following code chunk, which is a rewrite of the above piece of code:
for x in range(20):
if x >= 20:
print(x+1)
else:
print(x+5)
Output:: [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24]

Nested List Comprehensions:


Apart from conditionals, you can also adjust your list comprehensions by nesting them
within other list comprehensions. This is handy when you want to work with lists of lists:
generating lists of lists, transposing lists of lists or flattening lists of lists to regular lists.
Take a look at the following example:

list_of_list = [[1,2,3],[4,5,6],[7,8]]
list = [y for x in list_of_list for y in x]
print(list)
output:: [1, 2, 3, 4, 5, 6, 7, 8]

Let's now consider another example, where you see that you can also use two pairs of
square brackets to change the logic of your nested list comprehension:

matrix = [[1,2,3],[4,5,6],[7,8,9]]
list = [[row[i] for row in matrix] for i in range(3)]
print(list)
output:: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

You can rewrite the code chunk above to a nested for loop as fallows,
matrix = [[1,2,3],[4,5,6],[7,8,9]]
transposed = []
for i in range(3):
transposed_row = []
for row in matrix:
transposed_row.append(row[i])
transposed.append(transposed_row)
print(transposed)
output:: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy